How to set an auto-increment ID field in SQL Server?

To set an auto-increment id field in SQL Server, the commonly used property isIDENTITY. The specific steps are as follows:

  1. When creating a table, use the IDENTIY keyword when defining the id field, and specify the starting value and increment value.
CREATE TABLE TableName
(
    id INT IDENTITY(1,1) PRIMARY KEY,
    ...
)
  1. When inserting a new record, there is no need to specify a value for the id field as the database will automatically assign a unique incremental value to this field.
INSERT INTO TableName (column1, column2, ...)
VALUES (value1, value2, ...)
  1. If you need to retrieve the id value of the just inserted record, you can use the @@IDENTITY or SCOPE_IDENTITY() function.
SELECT @@IDENTITY
SELECT SCOPE_IDENTITY()

This allows you to set an auto-incrementing id field in SQL Server to achieve the function of generating unique values automatically.

bannerAds