
 
 | 
| 技术资料  > ASP技术 > 客户端相关 : 使用@IDENTITY |  
使用@IDENTITY March 25,2004 |  
基本知识 
 
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 |  
 
 | 
  
Copyright © 2001-2008 Shenzhen Hiblue Software Team All rights reserved