2016-01-21 58 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