在表中创建标识列。该属性用于 CREATE TABLE 和 ALTER TABLE 语句。
语法
IDENTITY [ (seed,increment) ]
参数
seed
向表中加载第一行时所使用的值。increment
加到所加载上一行的标识值上的增量值。备注
必须同时指定 seed 和 increment,或者不指定任何值。如果不指定任何值,则默认为 (1,1)。
注释
在 Microsoft SQL Server Compact 中,IDENTITY 属性只能在数据类型为 integer 或 bigint 的列上创建。一个表只能有一个 IDENTITY 列。
示例
说明
下面的示例演示如何创建第一列为 IDENTITY 列的表,以及如何将值插入表中和从表中删除值。
代码
-- Create the Tool table.
CREATE TABLE Tool(
ID INT IDENTITY NOT NULL PRIMARY KEY,
Name VARCHAR(40) NOT NULL
)
-- Insert values into the Tool table.
INSERT INTO Tool(Name) VALUES ('Screwdriver')
INSERT INTO Tool(Name) VALUES ('Hammer')
INSERT INTO Tool(Name) VALUES ('Saw')
INSERT INTO Tool(Name) VALUES ('Shovel')
-- Create a gap in the identity values.
DELETE Tool
WHERE Name = 'Saw'
-- Select the records and check results.
SELECT *
FROM Tool
-- Insert an explicit ID value of 3.
-- Query returns an error.
INSERT INTO Tool (ID, Name)
VALUES (3, 'Garden shovel')
-- SET IDENTITY_INSERT to ON.
SET IDENTITY_INSERT Tool ON
-- Insert an explicit ID value of 3.
INSERT INTO Tool (ID, Name)
VALUES (3, 'Garden shovel')
-- Select the records and check results.
SELECT *
FROM Tool
-- Drop Tool table.
DROP TABLE Tool