When using multiple WHEN MATCHED statements, do they all execute, or does only one get executed?

前端 未结 3 1318
感情败类
感情败类 2021-02-07 02:32

If I have multiple WHEN MATCHED statements in a MERGE statement, do they all execute if they\'re true?

My example:

DECLARE @X bit = NULL;

--skipping the         


        
3条回答
  •  误落风尘
    2021-02-07 03:29

    To answer your question, yes, it will only run a single match and then break. However, if you'd like to have logic to allow for conditional matching in the update, the CASE statement is rather useful for this.

    Something like this as an example:

    MERGE INTO YourTable
    USING (VALUES (1, 1, NULL), (0, 0, NULL), (0, 1, NULL), (1, 0, NULL))
           T2 (a2,b2,c2)
    ON a = a2 AND b = b2
    WHEN MATCHED  THEN
        UPDATE SET c = 
          CASE 
            WHEN a = 1 THEN 0
            WHEN b = 1 THEN 1
            ELSE NULL
          END        
    WHEN NOT MATCHED THEN
        INSERT (a, b) VALUES (a2, b2);
    
    SELECT * FROM YourTable ORDER BY a,b;
    
    • SQL Fiddle Demo

    And the results:

    A   B   C
    --------------
    0   0   (null)
    0   1   1
    1   0   0
    1   1   0
    

提交回复
热议问题