博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Identity相關知識

Posted on 2011-01-23 00:28  ☆Keep★Moving☆  阅读(159)  评论(0编辑  收藏  举报

对于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,你最好一个简单的存储过程来解决这个问题。
use master
go
if object_id('identity_t1') is not null
begin
drop table identity_t1
end
if object_id('identity_t2') is not null
begin
drop table identity_t2
end
create table identity_t1(c1 int identity,c2 datetime default(getdate()))
create table identity_t2(c1 int identity,c2 datetime default(getdate()))
insert into identity_t1 values (getdate())
insert into identity_t2 values (getdate())
insert into identity_t2 values (getdate())
select @@identity as identity_value_for_all_tables
select scope_identity() as scope_identity_value_for_all_tables
select ident_current('identity_t1') as ident_current_value_for_identity_t1
go
if object_id('identity_t1') is not null
begin
drop table identity_t1
end
if object_id('identity_t2') is not null
begin
drop table identity_t2
end
----注:IDENT_CURRENT('table') 是全局变量,如果Insert过程太长时间,有可能就会拿了别人-----Insert这个Table的ID,而SCOPE_IDENTITY()是同一进程内取得的值。最确保正确的办法:----select @@IDENTITY 和 Select SCOPE_IDENTITY()或 Select IDENT_CURRENT('table')相比较。