1

我正在努力使用 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
4

2 回答 2

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
于 2012-10-12T15:49:50.683 回答
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因为您在每种情况下都更新不同的列。

于 2012-10-12T15:55:14.143 回答