开发者

Update with sub select - How to handle NULL values?

I'm trying an update with a conditional sub-select which could return null...

UPDATE 
aTable SET 
aColumn = 
(   
    SELECT TOP 1    
        CASE 
   开发者_C百科         WHEN bTable.someColumn = 1 THEN someValue1 
            WHEN bTable.someColumn = 2 THEN someValue2 
            ELSE someValue3
        END  
    FROM         
        bTable
    WHERE
        bTable = @someCriteria
    ORDER BY
        someSortColumn
) WHERE 
aTable.id = @someId;

If the "bTable = @someCriteria" clause causes no results to be returned from the SELECT, it attempts to insert a NULL into "aColumn", which in this case is a NOT NULL column.

Question

How do I get it to simply leave "aColumn" alone in this circumstance?

Many thanks.


...
aColumn = 

    ISNULL(
        (   
            SELECT TOP 1    
                CASE 
                    WHEN bTable.someColumn = 1 THEN someValue1 
                    WHEN bTable.someColumn = 2 THEN someValue2 
                    ELSE someValue3
                END  
            FROM         
                bTable
            WHERE
                bTable = @someCriteria
            ORDER BY
                someSortColumn
        ), aColumn)
...


UPDATE A SET 
aColumn = B.Value 
FROM aTable AS A
  CROSS JOIN  
            (   
                SELECT TOP 1    
                    CASE 
                        WHEN bTable.someColumn = 1 THEN someValue1 
                        WHEN bTable.someColumn = 2 THEN someValue2 
                        ELSE someValue3
                    END  
                FROM         
                    bTable
                WHERE
                    bTable = @someCriteria
                ORDER BY
                    someSortColumn
            ) AS B(Value)
WHERE            
  A.id = @someId;

Difference between my answer and answer by gbn is that here column aColumn is not modified. I think that the isnull(..., aColumn) actually updates the value so if you have an update trigger it will fire.


UPDATE aTable
SET aColumn = s.Value
FROM (   
    SELECT TOP 1    
        CASE 
            WHEN bTable.someColumn = 1 THEN someValue1 
            WHEN bTable.someColumn = 2 THEN someValue2 
            ELSE someValue3
        END AS Value
    FROM         
        bTable
    WHERE
        bTable = @someCriteria
    ORDER BY
        someSortColumn
) s
WHERE aTable.id = @someId
  AND s.Value IS NOT NULL;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜