我試圖找到由exec(@Sql)插入的插入記錄的標識值,但似乎exec()在不同的作用域中執行。如何在調用exec(@Sql)後獲取標識值
/*
create table [dbo].[__Test](
[id] [int] IDENTITY(1,1) NOT NULL,
[description] [varchar](100) NULL
) ON [PRIMARY]
GO
*/
declare @Sql varchar(512)
set @Sql = 'insert into [dbo].[__Test] ([description]) values (''Some text'')'
exec (@Sql)
select
@@IDENTITY as [@@IDENTITY],
scope_identity() as [scope_identity],
ident_current('__Test') as [ident_current]
/*
if exists(select * from sys.objects where object_id = object_id('[dbo].[__Test]') and type='U')
drop table [dbo].[__Test]
GO
*/
回報:
@@IDENTITY scope_identity ident_current
---------- -------------- -------------
14 NULL 14
,如果有上__Test觸發,返回:
@@IDENTITY scope_identity ident_current
---------- -------------- -------------
6 NULL 14
所以@@ IDENTITY可能是觸發插入,執行不在範圍內和ident_current()可能來自另一個用戶。
有什麼辦法可靠地從exec()插入的身份值找到身份值?
那會做很好,謝謝。 – avenmore 2010-02-19 14:12:13