我正在使用SQL Management Studio 2012,并且有一个存储过程,该存储过程在执行时会插入如下表中
Column1 Column2 Column3
AA AA1 NULL
AB AB1 NULL
AC AC1 NULL
我必须手动填写NULL值(我知道这并不理想,但这是我发现自己的困境)
Column1 Column2 Column3
AA AA1 1234 --manual input
AB AB1 2468 --manual input
AC AC1 3579 --manual input
最初,我的存储过程设置如下:
ALTER PROCEDURE [usp_My_Stored_Procedure]
AS BEGIN
DELETE table1
INSERT table1
Select * from (
select
Column1,Column2,Column3
from another table
where Column3 IS NULL
) as SP
;
END
现在,当执行该操作时,将删除我在第3列中输入的所有内容。如果摆脱了“ DELETE table1”并保留INSERT,它将继续复制所有内容。我只需要它来更新出现的新行。
在下面的Zaynuls回答的帮助下,我现在尝试了以下方法
ALTER PROCEDURE [usp_My_Stored_Procedure]
AS BEGIN
MERGE Table1 as d
USING SP as s
ON (d.Column1 = S.Column1)
WHEN NOT MATCHED BY TARGET THEN
INSERT (Column1, Column2, Column3 )
VALUES (s.Column1, s.Column2, s.Column3)
WHEN MATCHED THEN
UPDATE SET d.Column1 = s.Column1, d.Column2 = s.Column2, d.Column3 = s.Column3
WHEN NOT MATCHED BY SP THEN DELETE
Select * from (
select
Column1,Column2,Column3
from another table
where Column3 IS NULL
) as SP
;
END
这没有用,以为我对来源和目的地感到困惑。 在这种情况下,我将目标用作表,而我要输入数据(“ Table1”),将源用作派生表名(SP)
答案 0 :(得分:0)
使用如下所示的合并,假设您的2个表的源和目标是
merge destination as D
using Source as S
on (D.Column1=S.Column1)
when not matched by Target then
Insert(Column1,Column2,Column3)
Values(s.Column1,s.Column2,S.Column3)
when matched then
Update set D.Column2=S.Column2, D.Column3=S.Column3
when not matched by Source then
Delete