欢迎光临
我们一直在努力

使用@IDENTITY

建站超值云服务器,限时71元/月

基本知识

1. identity 列不能由用户直接更新,它是由系统自动维护的。

2.该列数据类型必须为数值型:int, smallint, tinyint, decimal or numeric with scale 0。

3.该列不能为 null。

4.不能在该列上设置缺省值。

5.递增量只能为整形(比如:1,2,-3)。不能为小数,也不能为0。

6.基值(种子值 seed)可以由用户设置,缺省值为1。

理解 @@identity

@@identity 返回最后一个插入 identity 的值,这些操作包括:insert, select into,或者 bulk copy。如果在给没有 identity 列的其他表插入记录,系统将其置为 null。如果有多行记录插入到 identity 表中,@@identity 表示最后一个产生的值。如果触发了某个触发器,并且这个触发器执行向另一个带有 identity 列的表的插入操作,@@identity 将返回这个由触发器产生的值。如果这个触发器插入的表中不包含 identity 列,那么 @@identity 将为 null。如果插入操作失败,@@identity 值依然会增加,所以 identity 不保证数据的连续性。

@@identity 是当前连接的全局变量,只对当前连接有效。也就是说,如果断开连接再重新连接后,@@identity 为 null。以 ado 来说,@@identity 在 connection 对象打开和关闭期间是有意义的,即在 connection 对象的存在范围内有效。在 mts 组件中,从打开连接到显式的关闭连接(connection.close)或者到调用了 setabort,setcomplete之前,在这期间,@@identity 有意义。

使用 truncate table 语句会使 identity 列重新开始计算。

得到 @@identity 的值

有三种方法(以下代码均使用 vbscript)

方法一:

dim conn, strsql, rs

set conn = createobject("adodb.connection")

open a connection to the database

conn.open("dsn=mydsn;uid=myuid;pwd=mypwd;")

insert a new record into the table

strsql = "insert into mttable (columnname) values (something)"

execute the sql statement

conn.execute(strsql)

get the @@identity.

strsql = "select @@identity as newid"

set rs = conn.execute(lssql)

newid = rs.fields("newid").value

close the connection

conn.close()

set conn = nothing

方法二(仅限于 ado 2.0 以上):

dim conn, strsql, rs

set conn = createobject("adodb.connection")

open a connection to the database

conn.open("dsn=mydsn;uid=myuid;pwd=mypwd;")

insert a new record into the table

lssql = "insert into mytable (columnname) values (something);" &_

"select @@identity as newid;"

execute the sql statement

set rs = conn.execute(lssql)

get the second resultset into a recordset object

set rs = rs.nextrecordset()

get the inserted id

newid = rs.fields("newid").value

close the connection

conn.close()

set conn = nothing

方法三:

dim conn, strsql, rs

set conn = createobject("adodb.connection")

open a connection to the database

conn.open("dsn=mydsn;uid=myuid;pwd=mypwd;")

insert a new record into the table

strsql = "set nocount on;" &_

"insert into mytable (columnname) values (something);" &_

"select @@identity as newid;"

execute the sql statement

set rs = conn.execute(lssql)

get the inserted id

newid = rs.fields("newid").value

close the connection

conn.close()

set conn = nothing

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » 使用@IDENTITY
分享到: 更多 (0)