SQL Server 2012 - 如果满足条件,则更新列(CASE)否则不更新

时间:2015-07-27 14:13:56

标签: sql-server sql-server-2012 case

在下面的示例中,列' SecondColumn'和' ThirdColumn'每次代码块运行时都会更新。 ' FirstColumn'将更新为存储在变量@NumberOfRows中的值(只要它> 0)。

我遇到的问题是当@NumberOfRows为0或更低时,' FirstColumn'将被设置为NULL。

是否有可能对此进行调整,以便@NumberOfRows为0或更小,那么' FirstColumn'根本不更新而不是将列设置为NULL?

DECLARE 
     @NumberOfRows INT = 0
    ,@NewValue DATETIME = GETDATE()
    ,@Other INT = 99

BEGIN
    UPDATE x
    SET  x.FirstColumn = (CASE WHEN @NumberOfRows > 0 THEN @NewValue END)
        ,x.SecondColumn = SYSDATETIMEOFFSET()
        ,x.ThirdColumn = @Other
    FROM TestTable x
    WHERE x.ID = 100
END

2 个答案:

答案 0 :(得分:5)

最简单的方法是使用当前值更新字段。

DECLARE 
     @NumberOfRows INT = 0
    ,@NewValue DATETIME = GETDATE()
    ,@Other INT = 99

BEGIN
    UPDATE x
    SET  x.FirstColumn = (CASE WHEN @NumberOfRows > 0 THEN @NewValue ELSE x.FirstColumn END)
        ,x.SecondColumn = SYSDATETIMEOFFSET()
        ,x.ThirdColumn = @Other
    FROM TestTable x
    WHERE x.ID = 100
END

答案 1 :(得分:0)

如果@NumberOfRows <= 0

,请勿执行给定列的更新
DECLARE 
     @NumberOfRows INT = 0
    ,@NewValue DATETIME = GETDATE()
    ,@Other INT = 99

BEGIN

    IF @NumberOfRows > 0
        BEGIN
            UPDATE x
            SET  x.FirstColumn = @NewValue
                ,x.SecondColumn = SYSDATETIMEOFFSET()
                ,x.ThirdColumn = @Other
            FROM TestTable x
            WHERE x.ID = 100
        END
    ELSE
        BEGIN
            UPDATE x
            SET  x.SecondColumn = SYSDATETIMEOFFSET()
                ,x.ThirdColumn = @Other
            FROM TestTable x
            WHERE x.ID = 100
        END
END