SCOPE_IDENTITY()多次插入

时间:2016-01-21 21:17:36

标签: sql-server sql-server-2008 tsql sql-server-2005

如何避免这些类型可以为每个标识插入值捕获值并插入其他表

Insert into LookupTables (a, b, c, d, e, OtherInfo, SortOrder)
Values (a, b, c, d, e, NULL, NULL)

DECLARE @LookupID INT = SCOPE_IDENTITY() 

Insert into LookupTables (a, b, c, d, e, OtherInfo, SortOrder)
Values (a, b, c, d, e, @LookupID, NULL)

Insert into LookupTables (a, b, c, d, e, OtherInfo, SortOrder)
Values (a, b, c, d, e, NULL, NULL)

DECLARE @LookupID2 INT = SCOPE_IDENTITY() 

Insert into LookupTables (a, b, c, d, e, OtherInfo, SortOrder)
Values (a, b, c, d, e, @LookupID2, NULL)

3 个答案:

答案 0 :(得分:1)

如果排序顺序是唯一的(我怀疑它是)

然后使用values(),(),()插入all并使用output子句

我这样做但我现在没有时间查找代码

答案 1 :(得分:1)

declare @t table 
(
    id  int not null identity,
    a   int ,
    b   int ,
    c   int ,
    OtherInfo int
);


insert into @t (a, b, c)
output inserted.a, inserted.b, inserted.c, inserted.id 
into LookupTables (a, b, c, OtherInfo)
values (1,1,1),(2,2,2),(3,3,3),(4,4,4),(5,5,5);

select * from @t;

SQL Fiddle

答案 2 :(得分:0)

我想你问的是如何在不为每个最后插入的标识值声明变量的情况下这样做。当然,您实际上可以只重用一个变量。但更容易的是完全跳过变量。

Insert into LookupTables (a, b, c, d, e, OtherInfo, SortOrder)
Values (a, b, c, d, e, NULL, NULL)

Insert into LookupTables (a, b, c, d, e, OtherInfo, SortOrder)
Values (a, b, c, d, e, SCOPE_IDENTITY(), NULL)

Insert into LookupTables (a, b, c, d, e, OtherInfo, SortOrder)
Values (a, b, c, d, e, NULL, NULL)

Insert into LookupTables (a, b, c, d, e, OtherInfo, SortOrder)
Values (a, b, c, d, e, SCOPE_IDENTITY(), NULL)