MERGE - conditional “WHEN MATCHED THEN UPDATE”

梦想的初衷 提交于 2021-02-17 21:14:10

问题


The highlights in the image below shows the logic I want to implement. I realize the syntax is incorrect.

Is there a way to conditionally update a record in a MERGE statement only if it the value of one of its columns in the target table is NULL, and the corresponding value in the source table is not null?

How would you suggest re-writing this?

MERGE dbo.input_311 AS [t]
USING dbo.input_311_staging AS [s]
ON ([t].[unique key] = [s].[unique key])
WHEN NOT MATCHED BY TARGET
    THEN INSERT(t.[Created Date]) VALUES(s.[Created Date])
WHEN MATCHED
    THEN UPDATE SET(t.[Created Date] = s.[Created Date]
                WHERE s.[Created Date] IS NOT NULL
                AND t.[Created Date] IS NULL)
OUTPUT deleted.*, $action, inserted.*;
GO

回答1:


You might be able to use When Matched And (s.[Created Date] Is Not Null And t.[Created Date] Is Null) Then Update ....



来源:https://stackoverflow.com/questions/13924238/merge-conditional-when-matched-then-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!