Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MERGE - conditional "WHEN MATCHED THEN UPDATE"

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
like image 693
sion_corn Avatar asked Dec 17 '12 23:12

sion_corn


People also ask

Is MERGE into faster than update?

The UPDATE statement will most likely be more efficient than a MERGE if the all you are doing is updating rows. Given the complex nature of the MERGE command's match condition, it can result in more overhead to process the source and target rows.

Can we use where condition in MERGE statement?

The MERGE statement doesn't have a WHERE clause.

Can we use CTE in MERGE statement?

Common Table expressions are part of an SELECT-Statement, but cannot used everywhere where a SELECT-statement is allowed (sometimes only a FULL-Select - without CTE is allowed, for example in an UPDATE-Statement).

How many when matched clause can be used in a MERGE statement?

The MERGE statement can have, at most, two WHEN MATCHED clauses. If two clauses are specified, the first clause must be accompanied by an AND <search_condition> clause. For any given row, the second WHEN MATCHED clause is only applied if the first isn't.


1 Answers

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

like image 189
Laurence Avatar answered Oct 01 '22 09:10

Laurence