如何可靠地获取插入到不同数据库中的行的标识 ID
How can I reliably get identity ID of a row inserted into a different database
scope_identity()
获取同一 SQL 服务器上不同数据库中新插入的行的身份 ID 的可靠方法吗?
我有两个数据库 DB_A 和 DB_B 位于同一个 SQL 服务器上 (2012)
我有一个驻留在 DB_A 中的存储过程,其中一行被插入到 DB_B 中。需要获取该行的标识ID才能继续存储过程。
insert into DB_B.dbo.CustAddress values (@newAddress);
select @newID = scope_identity()
我已经在我的测试服务器上测试了这种方法,它工作得很好。但是,似乎有时(罕见且难以捕捉)没有获得 ID。 ID 在生产服务器上只是 0(不像返回错误的 ID),这是一个繁忙的环境,有大量来自各种来源的 DB_B 插入。由于没有ID,虽然没有SQL异常,但我无法验证插入是否成功完成。
我的问题是,我可以信任返回的 ID 吗?在什么情况下 SQL 无法以这种方式返回新插入行的身份 ID?
使用output
子句:
declare table @ids (id int);
insert into DB_B.dbo.CustAddress
output inserted.id into @ids
values (@newAddress);
select *
from @ids;
scope_identity()
获取同一 SQL 服务器上不同数据库中新插入的行的身份 ID 的可靠方法吗?
我有两个数据库 DB_A 和 DB_B 位于同一个 SQL 服务器上 (2012) 我有一个驻留在 DB_A 中的存储过程,其中一行被插入到 DB_B 中。需要获取该行的标识ID才能继续存储过程。
insert into DB_B.dbo.CustAddress values (@newAddress);
select @newID = scope_identity()
我已经在我的测试服务器上测试了这种方法,它工作得很好。但是,似乎有时(罕见且难以捕捉)没有获得 ID。 ID 在生产服务器上只是 0(不像返回错误的 ID),这是一个繁忙的环境,有大量来自各种来源的 DB_B 插入。由于没有ID,虽然没有SQL异常,但我无法验证插入是否成功完成。
我的问题是,我可以信任返回的 ID 吗?在什么情况下 SQL 无法以这种方式返回新插入行的身份 ID?
使用output
子句:
declare table @ids (id int);
insert into DB_B.dbo.CustAddress
output inserted.id into @ids
values (@newAddress);
select *
from @ids;