How to set up automatic data increment in SQL Server?

In SQL Server, you can use an auto-incrementing identity column to achieve data incrementation automatically. Here is an example demonstrating how to create a table with an auto-incrementing identity column.

CREATE TABLE ExampleTable
(
    ID INT IDENTITY(1,1) PRIMARY KEY,
    Column1 VARCHAR(50),
    Column2 INT
)

In the example above, the ID column is defined as an auto-increment identity column, starting from 1 and increasing by 1 each time. When inserting a new record, there is no need to specify the value of the ID column, as the system will automatically generate a unique ID value for each record.

When inserting data, you can use the following statement:

INSERT INTO ExampleTable (Column1, Column2)
VALUES ('Value1', 100)

In this case, the ID column will increment automatically and the system will assign a unique ID value to the newly inserted record.

It is important to note that auto-incremental identity columns can only be used for columns of integer types. If the automatic increment needs to be implemented on columns of other types, SEQUENCE or other methods can be used to achieve it.

bannerAds