我在MSSQL中有一个insert语句,如下所示:
INSERT INTO A(KeyId, KeyName, Name)
SELECT ('?','?',BName)FROM B
从另一个表D
中检索KeyId和KeyName的值表B-表C映射是BName = XName 表C-表D映射是Xname = XName B中有1000条记录需要插入A.如何为同一个SP编写SP?
表A列 - KeyId,KeyName,Name 表B列 - Id,BName 表C列 - XName 表D列 - KeyId,KeyName,XName
答案 0 :(得分:2)
在SQL Server 2005及更高版本中,您可以使用outer apply
:
insert into A(KeyId, KeyName, Name)
select
CALC.KeyId,
CALC.KeyName,
B.Name
from B
outer apply (select KeyId,KeyName from C where C.Name = 'SomeNameFromTableB') as CALC
对于以前的版本,您可以声明变量,用值填充它并使用这些变量:
declare @KeyId bigint, @KeyName nvarchar(max)
select @KeyId = KeyId, @KeyName = KeyName FROM C WHERE Name = 'SomeNameFromTableB'
insert into A(KeyId, KeyName, Name)
select
@KeyId,
@KeyName,
B.Name
from B
更新从OP的评论:
Name ='SomeNamefromTableB'的值实际上是我插入的值,即B.Name
因此,在这种情况下,您可以使用join:
insert into A(KeyId, KeyName, Name)
select
C.KeyId,
C.KeyName,
B.BName
from B
left outer join C on C.XName = B.BName
答案 1 :(得分:0)
试试这个:
INSERT INTO A(KeyId,KeyName,Name)
SELECT c.KeyId,
c.KeyName,
c.XName
FROM C
JOIN B
ON c.XName = b.Name
这将插入来自c.XName
中b.Name
所在的C的那些行。