次の小さなスクリプトを検討してください。
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
2 番目の解決策は機能し、すべて問題ありません。問題ではないことはわかっていますが、継続性のために、データベーステーブルに列が存在する順序で挿入を行うのが好きです。どうすればそれを達成できますか?次の試行は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))
EDIT:Webページでは、次のような構造のテーブルに新しい行が入力されます
QuizId,StudentId,DateTaken
(QuizId is an identity column)
次のようなクイズの質問がある別のテーブルがあります
QuestionId,Question,CorrectAnswer
任意の数のクイズに任意の数の質問を含めることができるため、この例でtestJunction
はその多対多を解決します。したがって、クイズには多くの質問があるため、SCOPE_IDENTITY を繰り返す必要があります。