我有代码,根据值TestStatusId
,这三个更新中只有一个会运行 UPDATE UserTest
SET StartedDate = @Date,
TestStatusId = 2
WHERE UserTestId = @UserTestId
AND UserId = @UserId
AND TestStatusId = 1
UPDATE UserTest
SET StartedDate = @Date,
TestStatusId = 2
WHERE UserTestId = @UserTestId
AND UserId = @UserId
AND TestStatusId = 3
UPDATE UserTest
SET StartedDate = @Date,
TestStatusId = 10
WHERE UserTestId = @UserTestId
AND UserId = @UserId
AND TestStatusId = 4
如果有办法可以将这些更新合并到一次更新中,有没有人有任何建议?
答案 0 :(得分:5)
是的,有:
UPDATE UserTest
SET StartedDate = @Date,
TestStatusId = CASE WHEN TestStatusId IN (1,3) THEN 2 ELSE 10 END
WHERE UserTestId = @UserTestId
AND UserId = @UserId
AND TestStatusId IN (1,3,4);