2016-01-21 59 views
0

我怎样才能避免这些类型可我对每个标识插入获取价值和其他表SCOPE_IDENTITY()多重插入

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) 
+0

我不了解这里的问题。什么是问题或你想要做什么?您可以跳过声明变量,并将SCOPE_IDENTITY()作为列值。 –

+0

我从第一个获得标识值,并将该标识插入到同一张表中的第二个语句中。不再声明每次都可以获取值,以便我可以插入多个记录 – Aswin

+0

不,没有“神奇”的方式做到这一点 - 你正在做的是完美的,它是**的方式去.. –

回答

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) 
+0

这是好的,但我们可以做更简单的方式.. !! – Aswin

+1

它可以更简单吗?你有4个单独的插入吗?不知道还有什么可以做到“简单” –

+0

好奇,如果downvoter会照顾评论。 –

1

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

然后插入所有的值(),(),(),并使用一个output条款

我做的正是这一点,但我没有时间,现在来查找代码

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