[英]Inserting SCOPE_IDENTITY() into a junction table
考虑以下小脚本:
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,因为测验中有很多问题。
您需要输出子句。 在BOL中查找。
尝试这种方式:
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
失败的版本
insert into #testJunction(testId,otherId)
select SCOPE_IDENTITY(),(select top 10 OtherId from OtherTable)
将在第一列中插入具有scope_identity()
一行,在第二列中插入一组10个值。 一列不能有集合,因此一个列将失败。
一个有效的
insert into #testJunction(otherId,testId)
select top 10 OtherId ,(select SCOPE_IDENTITY())
from OtherTable
将在第一列中插入OtherTable
具有OtherId
10行,在第二列中插入scope_identity()
的标量值。
如果您需要切换列的位置,它将看起来像这样。
insert into #testJunction(testId,otherId)
select top 10 SCOPE_IDENTITY(), OtherId
from OtherTable
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.