很简单,我有两个表Source和Target.
declare @Source table (SourceID int identity(1,2), SourceName varchar(50))
declare @Target table (TargetID int identity(2,2), TargetName varchar(50))
insert into @Source values ('Row 1'), ('Row 2')
Run Code Online (Sandbox Code Playgroud)
我想将所有行移动@Source到@Target并知道TargetID每个行,SourceID因为还有表格SourceChild,TargetChild并且需要复制,我需要将新行添加TargetID到TargetChild.TargetIDFK列中.
有几个解决方案.
scope_identity()填充FK TargetChild.@Target并插入SourceID.然后,您可以加入该列以获取TargetIDFK中的内容TargetChild.SET IDENTITY_INSERT OFFfor @Target和处理自己分配新值.您将获得一个然后使用的范围TargetChild.TargetID.我不是那么喜欢他们中的任何人.我到目前为止使用的是游标.
我真正想要做的是使用outputinsert语句的子句.
insert into @Target(TargetName)
output inserted.TargetID, S.SourceID
select SourceName
from @Source as …Run Code Online (Sandbox Code Playgroud) 考虑表SAMPLE:
id integer
name nvarchar(10)
Run Code Online (Sandbox Code Playgroud)
有一个存储过程称为myproc.它只需要一个参数(即id)
给定一个名称作为参数,找到所有行name = @nameparameter并将所有这些ID传递给myproc
例如:
sample->
1 mark
2 mark
3 stu
41 mark
Run Code Online (Sandbox Code Playgroud)
当mark通过后,1 ,2 and 41将被传递到myproc个别.
即应发生以下情况:
execute myproc 1
execute myproc 2
execute myproc 41
Run Code Online (Sandbox Code Playgroud)
我无法触摸myproc也看不到它的内容.我只需将值传递给它.