2013-08-22 54 views
0

請看下面的小腳本:插入SCOPE_IDENTITY()爲結合表

create table #test 
(testId int identity 
,testColumn varchar(50) 
) 
go 
create table #testJunction 
(testId int 
,otherId int 
) 


insert into #test 
    select 'test data' 
    insert into #testJunction(testId,otherId) 
    select SCOPE_IDENTITY(),(select top 10 OtherId from OtherTable) 
--The second query here signifies some business logic to resolve a many-to-many 
--fails 

然而,這將工作:

insert into #test 
select 'test data' 
insert into #testJunction(otherId,testId) 
select top 10 OtherId ,(select SCOPE_IDENTITY()) 
from OtherTable 
--insert order of columns is switched in #testJunction 
--SCOPE_IDENTITY() repeated for each OtherId 

第二種解決方案作品,一切都很好。我知道這並不重要,但出於連續性的考慮,我喜歡按照數據庫表中列的順序進行插入操作。我怎麼能這樣?下面嘗試給出了subquery returned more than 1 value錯誤

insert into #test 
select 'test data' 
insert into #testJunction(otherId,testId) 
values ((select SCOPE_IDENTITY()),(select top 10 drugId from Drugs)) 

編輯: 網頁上的新行輸入表,其結構像

QuizId,StudentId,DateTaken 
(QuizId is an identity column) 

我有另一個表測驗題就像

QuestionId,Question,CorrectAnswer 

任何數量的測驗都可以有任意數量的問題,因此在此示例中testJunction 可續約很多很多。 Ergo,我需要重複SCOPE_IDENTITY,因爲測驗中有很多問題。

+1

不確定你的問題是什麼。你能提供示例數據嗎?第二個(你說的作品)爲所有十行插入相同的'SCOPE_IDENTITY()'。這是意圖嗎?如果是這樣,你爲什麼在乎插入順序是什麼? –

+0

是的,所以在這個例子中,測驗對象和測驗問題之間有多對多的關係。所以測驗1號可以有很多QuizQuestions。多對多的解決測驗和問題。 – wootscootinboogie

+0

@MartinSmith我在乎插入順序是什麼,只是因爲它感覺像是作弊,因爲我不知道如何以不同的方式做 – wootscootinboogie

回答

1

失敗

insert into #testJunction(testId,otherId) 
select SCOPE_IDENTITY(),(select top 10 OtherId from OtherTable) 

將在第一欄和第二欄的一組10個值插入一行與scope_identity()版本。一列不能有集合,以致失敗。

,工程

insert into #testJunction(otherId,testId) 
select top 10 OtherId ,(select SCOPE_IDENTITY()) 
from OtherTable 

的一個將在第一列和scope_identity()在第二列中的標量值插入來自OtherTable 10行與OtherId

如果您需要切換列的位置,它會看起來像這樣。

insert into #testJunction(testId,otherId) 
select top 10 SCOPE_IDENTITY(), OtherId 
from OtherTable 
+0

就是這樣。這不是一個很實際的問題,因爲我有一個可行的解決方案,但我只是想確保我沒有忽略SQL Server的一些愚蠢,單調的細節。 – wootscootinboogie

1

您需要輸出子句。在BOL中查找它。

+0

我還沒有使用它,猜對了。 – wootscootinboogie

1

試試這個方法:

Declare @Var int 
insert into #test 
select 'test data' 
select @var=scope_identity() 
insert into #testJunction(otherId,testId) 
select top 10 @var,drugId from Drugs 
相關問題