SQL Server MERGE command - how to trap if nothing qualified
With this command, we can specify something like:
WHEN MATCHED AND stm.StudentMark开发者_StackOverflow社区s > 250 THEN DELETE
But how do we trap if a record didn't qualify? For example, say stm.StudentMarks = 100? I get a syntax error if I try "ELSE".
I know this command is not typically used this way. But if it can do this, it will save me having to use a transaction, locks, and multiple SQL statements.
Try:
WHEN NOT MATCHED ....... THEN ......
to find those rows in the source that have no equivalent in the target (based on the ON ....
condition you've specified), or otherwise, you need to specify more / other expressions, e.g.
WHEN MATCHED AND stm.StudentMarks <= 250 THEN .....
Based on further learning, I have concluded that the way to do this is to use views / TVFs to get the correct data set. One could get the records complying to "IF ... THEN ..." and another could get the records complying to the ELSE. It would just been running two MERGE statements, which is no big deal.
Use a second
WHEN MATCHED THEN
without any extra conditions, it will only trigger one when clause and since the first gets all that matched with condition the second will only get those that matched all but the condition.
精彩评论