如何将以下两个查询合并为一个?
首先,我将所有检查员转移到不同的办公室,然后改变那些没有任何公开任务的检查员的办公室通道。
UPDATE
Inspectors
SET
OfficeID = 40
WHERE CountryID = 116 AND OfficeID = 5
UPDATE
Inspectors
SET
OfficeAccess = ',40'
FROM Inspectors i
WHERE NOT EXISTS (SELECT * from InspectionScope insp
INNER JOIN Assignments a ON a.AssignmentID = insp.AssignmentID
WHERE insp.InspectorID = i.InspectorID
AND a.CurrentStatus = 1)
AND i.CountryID = 116 AND i.OfficeID = 5
答案 0 :(得分:0)
UPDATE Inspectors
SET OfficeID = 40,
OfficeAccess = CASE WHEN a.CurrentStatus = 1 THEN OfficeAccess = ',40' ELSE OfficeAccess END--this is a varchar field
FROM Inspectors i
INNER JOIN InspectionScope insp
ON insp.InspectorID = i.InspectorID
LEFT JOIN Assignments a
ON a.AssignmentID = insp.AssignmentID
WHERE i.CountryID = 116 AND i.OfficeID = 5
答案 1 :(得分:0)
我不确定将它们组合起来是个好主意,但它应该是可能的。此方法使用left outer join
来保留Inspectors
表中的所有行。这允许设置OfficeId
。然后它使用case
语句来检查连接其余部分的匹配行(可能用于过滤):
UPDATE Inspectors
SET OfficeID = 40,
OfficeAccess = (Case when a.AssignmentId is not null then ',40' else OfficeAccess end)
FROM Inspectors i LEFT JOIN
InspectionScope insp
ON insp.InspectorID = i.InspectorID LEFT JOIN
Assignments a
ON a.AssignmentID = insp.AssignmentID AND a.CurrentStatus = 1
WHERE i.CountryID = 116 AND i.OfficeID = 5
答案 2 :(得分:0)
要结合两者,我会使用左连接并查找两种组合。
像...一样的东西。
UPDATE Inspectors
SET OfficeID = 40
, OfficeAccess = CASE
WHEN a.CurrentStatus <> 1
OR (
insp.InspectorID IS NULL
OR a.assignmentid IS NULL
)
THEN OfficeAccess = ',40'
ELSE NULL
END
FROM Inspectors i
LEFT JOIN InspectionScope insp
ON insp.InspectorID = i.InspectorID
LEFT JOIN Assignments a
ON a.AssignmentID = insp.AssignmentID
WHERE i.CountryID = 116
AND i.OfficeID = 5