考虑以下小脚本:
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
解决了多对多问题。因此,我需要重复 SCOPE_IDENTITY,因为测验中有很多问题。