我试图在存储过程中使用范围标识两次。
我的存储过程有3个元素,
第一个表ID工作正常但我似乎无法从第二个表中获取ID,然后使用该ID更新第一个。
这可能吗?
答案 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