我有以下代码:
-- First Table:
UPDATE [H$Agency Header]
SET [Booking Rating] = '1' --!!!!! CONDTION HERE !!!!!
FROM [H$Agency Header] AH
INNER JOIN #RatingLines RL1
ON RL1.[B_KEY] = AH.[Reservation No_]
WHERE RL1.[RTD_COMMENT] <> ''-- If the Booking have a comment inDB2
AND [Booking Rating] = '0' -- Get only Booking without Comments
如您所见,我将预订评级设置为1如果内部联接在两个表[H $ Agency Header]和#RatingLines中找到了公共行。现在我想说如果你没有找到它将它设置为&#39; 0&#39;。我可以在SET命令旁边放一个条件吗?如何?
答案 0 :(得分:3)
假设上述查询已解析,那么您可以使用LEFT JOIN
和CASE
执行所需操作。这需要将注释的条件从where
移动到on
子句:
UPDATE AH
SET [Booking Rating] = (CASE WHEN RLI.B_KEY IS NULL THEN '0' ELSE '1' END)
FROM [H$Agency Header] AH LEFT JOIN
#RatingLines RL1
ON RL1.[B_KEY] = AH.[Reservation No_] AND
RL1.[RTD_COMMENT] <> ''-- If the Booking have a comment inDB2
WHERE AH.[Booking Rating] = '0' -- Get only Booking without Comments
注意:如果[Booking Rating]
是整数,则不应将0
和1
放在单引号中。尽管它有效,但将数字列设置为字符串值会产生误导。
答案 1 :(得分:0)
你可以写成:
-- First Table:
UPDATE [H$Agency Header]
SET [Booking Rating] =
(case when RL1.[B_KEY] is null then '0' -- no match found
else '1'
end )
FROM [H$Agency Header] AH
left JOIN RatingLines RL1 -- change join to Left
ON RL1.[B_KEY] = AH.[Reservation No_] and RL1.[RTD_COMMENT] <> ''
--WHERE RL1.[RTD_COMMENT] <> ''-- If the Booking have a comment inDB2
--AND [Booking Rating] = '0'