在存储过程中为多个插入使用Scope Identity

时间:2014-04-12 09:21:34

标签: sql-server stored-procedures

我试图在存储过程中使用范围标识两次。

我的存储过程有3个元素,

  • 第一个插入到表中(我在这里使用范围标识来获取 新插入的行ID)
  • 第二个插入到第二个表,这将插入第一个中的ID 插入,我还使用范围标识来获取此新行的ID
  • 第3次更新第1个表,第2个表为新ID

第一个表ID工作正常但我似乎无法从第二个表中获取ID,然后使用该ID更新第一个。

这可能吗?

2 个答案:

答案 0 :(得分:2)

你应该能够这样做

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

答案 1 :(得分:-1)

使用类似这样的查询

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
相关问题