在下面的示例中,列' 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
答案 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