是否可以在一条语句中使用不同的条件更新多个列?

时间:2019-03-22 00:14:26

标签: sql sql-server sql-server-2017

如果所有列均为负,则需要将其设置为0。目前,我一次只做一列:

UPDATE #ListingRank SET Distance = 0 WHERE Distance < 0
UPDATE #ListingRank SET ActionDays = 0 WHERE ActionDays < 0
UPDATE #ListingRank SET Price = 0 WHERE Price < 0
UPDATE #ListingRank SET Beds = 0 WHERE Beds < 0
UPDATE #ListingRank SET Baths = 0 WHERE Baths < 0
UPDATE #ListingRank SET SqFt = 0 WHERE SqFt < 0

是否可以在单个语句中执行相同的操作?

1 个答案:

答案 0 :(得分:4)

您可以尝试使用CASE WHEN

UPDATE #ListingRank
SET Distance = (CASE WHEN Distance < 0 THEN 0 ELSE Distance END),
    ActionDays = (CASE WHEN ActionDays < 0 THEN 0 ELSE ActionDays END),
    Price = (CASE WHEN Price < 0 THEN 0 ELSE Price END),
    Beds = (CASE WHEN Beds < 0 THEN 0 ELSE Beds END),
    Baths = (CASE WHEN Baths < 0 THEN 0 ELSE Baths END),
    SqFt = (CASE WHEN SqFt < 0 THEN 0 ELSE SqFt END)