如何获得刚插入数据库的记录的id号?
1.sql server
对于sql server 2000来说,它提供了两个全新的函数(ident_current,scope_identity),并且改进了@@identity的不足.当你插入新记录后,可以调用函数:
print ident_current(table) 这将获得新的identity值,不管数据库中是不是有记录添加(这就避免了@@identity的连接限制)
或者:print scope_identity() 这将获得在当前存储过程,触发器等其他程序创建的最新记录的identity值.
而全局变量@@identity有一个问题,当对一张表执行insert时,如果该表有触发器程序在执行插入操作,然后,接着在另一张表中插入记录,这样返回@@identity值就是第二张表的identity值。
如果你用的不是sql server 2000,你最好一个简单的存储过程来解决这个问题。
create procedure myproc
@param1 int
as
begin
set nocount on
insert into sometable
(
intfield
)
values
(
@param1
)
set nocount off
select newid = @@identity
end
在asp中你可以这样做:
<%
fakevalue = 5
set conn = server.createobject("adodb.connection")
conn.open "<conn string>"
set rs = conn.execute("exec myproc @param1=" & fakevalue)
response.write "new id was " & rs(0)
rs.close: set rs = nothing
conn.close: set conn = nothing
%>
2.access
对于access,你可以用下面这样的方法:
<%
fakevalue = 5
set conn = server.createobject("adodb.connection")
conn.open "<conn string>"
conn.execute "insert into sometable(intfield) values(" & fakevalue & ")"
set rs = conn.execute("select max(id) from sometable")
response.write "new id was " & rs(0)
rs.close: set rs = nothing
conn.close: set conn = nothing
%>
然而对于多人同时向数据库中添加数据,我们就要利用记录集的adopenkeyset游标来防止出错。例如下面的例子:
<%
fakevalue = 5
set conn = server.createobject("adodb.connection")
conn.open "<conn string>"
set rs = server.createobject("adodb.recordset")
rs.open "select [intfield] from sometable where 1=0", conn, 1, 3
rs.addnew
rs("intfield") = fakevalue
rs.update
response.write "new id was " & rs("id")
rs.close: set rs = nothing
conn.close: set conn = nothing
%>
