添加一条新记录想返回主键就得认识一个这个东西@@IDENTITY的用法了…返回插入最后一条记录的一个标识值,只有主键值类型为IDENTITY的才有返回值,否则为NULL…
在没有使用ORM框架的情况下,添加一条新记录想返回主键就得认识一个这个东西@@IDENTITY的用法了(Nhibernate有添加就自己返回主键的方法).
@@IDENTITY是MSSqlServer返回插入最后一条记录的一个标识值,只有主键值类型为IDENTITY的才有返回值,否则为NULL.
如下脚本,创建三个表,一个是主表TestIdent,有一个自增主键,两个是子表TestChild1和TestChild2,以TestIdent表的主键来当外键.

Code
1
/**//*
2
使用@@IDENTITY示例
3
*/
4
5
CREATE TABLE TestIdent —建表TestIdent,主健为IDCol
6
(
7
IDCol int IDENTITY PRIMARY KEY
8
)
9
CREATE TABLE TestChild1 —建表TestChild1,主健为IDcol,外健为表TestIdent的IDCol
10
(
11
IDcol int PRIMARY KEY FOREIGN KEY REFERENCES TestIdent(IDCol)
12
)
13
CREATE TABLE TestChild2 —建表TestChild2,主健为IDcol,外健为表TestIdent的IDCol
14
(
15
IDcol int PRIMARY KEY REFERENCES TestIdent(IDCol)
16
)
17
18
DECLARE @Ident int
19
INSERT INTO TestIdent DEFAULT VALUES
20
21
SET @Ident=@@IDENTITY —@@IDENTITY的值为插入表TestIdent最后一条记录的主健值
22
—TestIdent表的主健是IDENTITY,所以@@IDENTITY有值
23
24
PRINT \’The value we got originally from @@IDENTYTY is \’ + CONVERT(varchar(2),@Ident)
25
PRINT \’The value currently in @@IDENTITY is \’ + CONVERT(varchar(2),@@IDENTITY)
26
27
INSERT INTO TestChild1 VALUES (@@IDENTITY)
28
29
PRINT \’The value we got originally from @@IDENTITY was \’ + CONVERT(varchar(2),@Ident)
30
31
IF(SELECT @@IDENTITY) IS NULL
32
PRINT \’The value currently in @@IDENTITY is NULL\’
33
ELSE
34
PRINT \’The value currently in @@IDENTITY is \’ + CONVERT(varchar(2),@@IDENTITY)
35
36
PRINT \’\’
37
38
INSERT INTO TestChild2 VALUES(@@IDENTITY) —@@IDENTITY为插入表TestChild1的最后一个记录的主健值
39
—因为TestChild1的主健不是IDENTITY型的,所以@@IDENTITY为空
40
运行结果为:

Code
1
2
(1 行受影响)
3
The value we got originally from @@IDENTYTY is 5
4
The value currently in @@IDENTITY is 5
5
6
(1 行受影响)
7
The value we got originally from @@IDENTITY was 5
8
The value currently in @@IDENTITY is NULL
9
10
消息 515,级别 16,状态 2,第 21 行
11
不能将值 NULL 插入列 \’IDcol\’,表 \’Test.dbo.TestChild2\’;列不允许有空值。INSERT 失败。
12
语句已终止。
运行结果第10行错误是因为表TestChild1的主键不是IDENTITY类型的.
在实际应用中,在INSERT INTO 语句后加上SELECT @@IDENTITY,Command对象就用ExecuteScalar()方法(执行查询,并返回所查询的结果集的第一行第一列,忽略其它行或列),即可返回最新插入记录的主键.使用存储过程也一样.最好的使用说明是在新用户注册后不用再登录就可保存该用户的对象.
@@IDENTITY就是得到这样一个主键,作用还有很多.