根据条件 Sql 服务器更新了 table?
Updated a table based on a condtion Sql server?
我有以下代码:
-- 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
如您所见,如果内部联接在两个表 [H$Agency Header] 和 #RatingLines 中找到公共行,我将预订评级设置为 1。现在我想说,如果您没有找到它,请将其设置为“0”。我可以在 SET 命令旁边加上条件吗?怎么样?
假设上面的查询解析,那么你可以用 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
放在单引号中。虽然它有效,但将数字列设置为字符串值会产生误导。
你可以这样写:
-- 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'
我有以下代码:
-- 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
如您所见,如果内部联接在两个表 [H$Agency Header] 和 #RatingLines 中找到公共行,我将预订评级设置为 1。现在我想说,如果您没有找到它,请将其设置为“0”。我可以在 SET 命令旁边加上条件吗?怎么样?
假设上面的查询解析,那么你可以用 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
放在单引号中。虽然它有效,但将数字列设置为字符串值会产生误导。
你可以这样写:
-- 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'