SQL Server Identity 特性的使用

来源:这里教程网 时间:2026-03-02 10:00:44 作者:

1. 创建一个带identity列的表
CREATE TABLE customer
(
cust_id smallint IDENTITY(100, 20) NOT NULL,
cust_name varchar(50) NOT NULL
)

2. 得到起点和步距
SELECT IDENT_SEED('customer'), IDENT_INCR('customer')


3.暂时禁止identity特性

SET IDENTITY_INSERT tablename ON


4.检索identity列的值


(1) @@IDENTITY
返回当前connection的最后一个identity值


INSERT customer (cust_name) VALUES ('AAA Gadgets')
SELECT @@IDENTITY

这个例子里,由于触发器的因素, @@IDENTITY返回的值甚至可能都不是最后一个cust_id的值,
有可能是另外一个表上的identity列的值.



(2)SCOPE_IDENTITY()
返回当前scope的最后一个identity的值,一个scope可以是一个SP,一个trigger,或者一个batch.

INSERT customer (cust_name) VALUES ('AAA Gadgets')
SELECT SCOPE_IDENTITY()


(3) IDENT_CURRENT('table_name')
不限联接和scope,查询那个identity的当前值(最后一个insert的值)

SELECT IDENT_CURRENT('customer')


5. Identity列的一些限制
(1) 必须是not null的
(2) 不能有default
(3) 一个表只能有一个identity列

[@more@]

相关推荐