使用子选择更新 - 如何处理NULL值?

时间:2011-06-17 10:18:59

标签: sql sql-server sql-update subquery

我正在尝试使用条件子选择进行更新,该子选择可以返回null ...

UPDATE 
aTable SET 
aColumn = 
(   
    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
) WHERE 
aTable.id = @someId;

如果“bTable = @someCriteria”子句导致没有从SELECT返回结果,它会尝试将NULL插入“aColumn”,在本例中是一个NOT NULL列。

问题

如何在这种情况下单独留下“aColumn”?

非常感谢。

3 个答案:

答案 0 :(得分:6)

...
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)
...

答案 1 :(得分:3)

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;

gbn的答案和答案之间的区别在于此处aColumn列未被修改。我认为isnull(..., aColumn)实际上更新了值,所以如果你有更新触发器它会触发。

答案 2 :(得分:1)

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;