請看下面的小腳本:插入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,因爲測驗中有很多問題。
不確定你的問題是什麼。你能提供示例數據嗎?第二個(你說的作品)爲所有十行插入相同的'SCOPE_IDENTITY()'。這是意圖嗎?如果是這樣,你爲什麼在乎插入順序是什麼? –
是的,所以在這個例子中,測驗對象和測驗問題之間有多對多的關係。所以測驗1號可以有很多QuizQuestions。多對多的解決測驗和問題。 – wootscootinboogie
@MartinSmith我在乎插入順序是什麼,只是因爲它感覺像是作弊,因爲我不知道如何以不同的方式做 – wootscootinboogie