各种SQL更新的case表达式

时间:2012-10-12 15:40:53

标签: sql sql-server tsql sql-update case

我正在努力使用case表达式来确定要生成哪个更新语句。以下是否可能,或者我应该为每次更新单独更新存储过程吗?

 IF (SELECT pick FROM warehouse WHERE order_no = @order_no and pick = @pick) is null
    CASE @pick 
    when 1 then
            UPDATE warehouse
            SET pick = @pick, startpickdate=@dchar, startpicktime=@tchar
            where order_no=@order_no
    when 2 then
            UPDATE warehouse
            SET pick = @pick, endpickdate=@dchar, endpicktime=@tchar
            where order_no=@order_no
    when 0 then
            UPDATE warehouse
            SET pick = @pick, endpickdate='', endpicktime='',startpickdate='', startpicktime=''
            where order_no=@order_no
END
GO

2 个答案:

答案 0 :(得分:1)

如果您想有条件地更新列,这种方法对您有用

UPDATE Warehouse
SET Pick = @pick
   , startPickDate = CASE @pick
                        WHEN 1 THEN @dchar
                        WHEN 2 THEN startPickDate
                        WHEN 0 THEN ''
                     END
   , startPickTime = CASE @pick
                        WHEN 1 THEN @tchar
                        WHEN 2 THEN startPickTime
                        WHEN 0 THEN ''
                     END
   , ...
WHERE order_no = @order_no

答案 1 :(得分:1)

CASE不用于T-SQL control-of-flow。因此,一种方法是继续使用IF(实际的流控制),这样可以使更新语句更简单,尽管每个分支都有一个:

IF (SELECT pick FROM warehouse WHERE order_no = @order_no AND pick = @pick) IS NULL BEGIN
    IF @pick = 1 BEGIN
        UPDATE warehouse
        SET pick = @pick, startpickdate=@dchar, startpicktime=@tchar
        WHERE order_no=@order_no
    END
    ELSE IF @pick = 2 BEGIN
        UPDATE warehouse
        SET pick = @pick, endpickdate=@dchar, endpicktime=@tchar
        WHERE order_no=@order_no
    END
    ELSE IF @pick = 0 BEGIN
        UPDATE warehouse
        SET pick = @pick, endpickdate='', endpicktime='',startpickdate='', startpicktime=''
        WHERE order_no=@order_no
    END
END
GO

无论如何,如果你处于存储过程中,你可能会发现它更易于维护,尽管这肯定是主观的。

我可能倾向于使用case这个方法而不是一个大的组合更新语句,因为你在每种情况下更新不同的列。