I am doing a MERGE statement in SQL Server 2008 R2. What I want to do is to have a more logic inside a NOT MATCHED branch:
WHEN NOT MATCHED THEN
INSERT (col1, col2, col3)
VALUES (SOURCE.col1, SOURCE.col2, SOURCE.col3)
OUTPUT INSERTED.col1, SOURCE.col4
INTO @Mapping
INSERT INTO @newChildren
( col1,
other columns,)
SELECT
( TARGET.col1,
other columns)
FROM @input
INNER JOIN @Mapping
ON @input.col1 = @Mapping.col2
EXECUTE Children_Create @newChildren;
The idea is to do use INSERT result to form another input to another stored procedure. But it seems control flow is not supported in SQL Server 2008 MERGE. I can’t put BEGIN/END to wrap this code. Any suggestions to overcome this limit?
The
INSERT,UPDATEandDELETEkeywords being parts ofMERGEmight have led you into thinking thatMERGEis a sort of compound statement. But it is only a complex one. The above-mentioned keywords introduce clauses ofMERGE, not separate corresponding statements, however much they may resemble the latter.So yes, if not as a separate procedure, yet at least outside
MERGEis how your additional inserts must be implemented.