【问题标题】:Using Scope Identity for multiple inserts within a stored procedure对存储过程中的多个插入使用 Scope Identity
【发布时间】:2014-04-12 09:21:33
【问题描述】:
我试图在一个存储过程中使用两次作用域标识。
我的存储过程有 3 个元素,
- 第一次插入表(我在这里使用范围标识来获取
新插入的行 ID)
- 第二个插入到第二个表中,这会从第一个表中插入 ID
插入,我也使用范围标识来获取这个新行的 id
- 第三次使用第二个表的新 ID 更新第一个表
第一个表 ID 工作正常,但我似乎无法从第二个表中获取 ID,然后使用该 ID 更新第一个表。
这可能吗?
【问题讨论】:
标签:
sql-server
stored-procedures
【解决方案1】:
你应该可以这样做
insert t1 values (...) -- first insert
declare @id1 as int = scope_identity() -- store the first id
insert t2 values (@id1, ...) -- second insert
update t1
set id2 = scope_identity() -- id from the second table
where id1 = @id1 -- primary key of the first table
【解决方案2】:
使用类似这样的查询
INSERT INTO [Table1] ([Id1] ,[Name],[DateCreated])
VALUES (@RId, @Name, GetDate())
DECLARE @NewId1 INT=0 -- recently inserted id in Table-1
SET @NewId1 = (SELECT @@IDENTITY)
INSERT INTO [Table2] ([Id2],[Id1],[Name],[DateCreated])
VALUES (@RId, @NewId1, @Name, GetDate()) -- insert the newly created Table-1 id into Table-2
DECLARE @NewId2 INT=0 -- recently inserted id in Table-2
SET @NewId2 = (SELECT @@IDENTITY)
INSERT INTO [Table3] ([Id3],[Id2],[Name],[DateCreated])
VALUES (@RId, @NewId2, @Name, GetDate()) -- insert the newly created Table-2 id into Table-3