我有一个SQL MERGE语句,如果存在一个值,则执行UPDATE(如果存在则执行INSERT)。当UPDATE发生时,我想在行中记录最后几个“历史”值,有点像这样:
MERGE into desttable as dest
USING sourcetable as src
on src.ref = dest.ref
WHEN MATCHED THEN
UPDATE SET dest.oldvalue3=dest.oldvalue2,
dest.oldvalue2=dest.oldvalue1,
dest.oldvalue1=dest.value,
dest.value=src.newvalue
WHEN NOT MATCHED THEN
INSERT ...
...基本上,现有的“值”被拖拽到“oldvalue1”,“oldvalue1”变成“oldvalue2”等。但是,当我运行它时,每列都被设置为“value” - UPDATE语句显然是立刻设置所有字段。有没有办法实现我想做的事情?
答案 0 :(得分:2)
您可以在left outer join desttable
子句中using
使用desttable
中的列作为更新源。
MERGE INTO desttable AS dest
USING (SELECT s.ref,
s.newvalue,
d.oldvalue2,
d.oldvalue1,
d.value
FROM sourcetable AS s
LEFT OUTER JOIN desttable AS d
ON s.ref = d.ref) AS src
ON src.ref = dest.ref
WHEN MATCHED THEN
UPDATE SET dest.oldvalue3=src.oldvalue2,
dest.oldvalue2=src.oldvalue1,
dest.oldvalue1=src.value,
dest.value=src.newvalue
;