我有以下查询:
SELECT CASE
WHEN @from < item.UpdatedOnCurr AND item.UpdatedOnCurr <= @till AND @till < item.UpdatedOnNext
THEN item.Id
ELSE '00000000-0000-0000-0000-000000000000'
END AS Id,
CASE
WHEN @from < item.UpdatedOnCurr AND item.UpdatedOnCurr <= @till AND @till < item.UpdatedOnNext
THEN item.PreviousId
ELSE item.Id
END AS PreviousId,
item.UUID,
CASE
WHEN @from < item.UpdatedOnCurr AND item.UpdatedOnCurr <= @till AND @till < item.UpdatedOnNext
THEN item.Json
ELSE NULL
END AS Json,
item.TableName,
item.PermissionId,
item.UpdatedOnCurr
FROM Computed item
WHERE item.Json IS NOT NULL AND (
(@from < item.UpdatedOnCurr AND item.UpdatedOnCurr <= @till AND @till < item.UpdatedOnNext)
OR (item.UpdatedOnCurr <= @from AND @from < item.UpdatedOnNext AND item.UpdatedOnNext <= @till)
);
我想简化它,即所有那些多个CASE
表达式都会削弱我的眼球,所以我想重新使用@from < item.UpdatedOnCurr AND item.UpdatedOnCurr <= @till AND @till < item.UpdatedOnNext
检查以便它赢得了#t每个选定的行执行多次......
那么你是如何实现这一目标的?
答案 0 :(得分:1)
使用 APPLY ,您可以清除其中一些重复逻辑。 CASE仍在那里..但我发现它更具可读性。
SELECT CASE m.m
WHEN 1
THEN item.Id
ELSE '00000000-0000-0000-0000-000000000000'
END AS Id,
CASE m.m
WHEN 1
THEN item.PreviousId
ELSE item.Id
END AS PreviousId,
item.UUID,
CASE m.m
WHEN 1
THEN item.Json
ELSE NULL
END AS Json,
item.TableName,
item.PermissionId,
item.UpdatedOnCurr
FROM Computed item
CROSS APPLY (
select
CASE
WHEN @from < item.UpdatedOnCurr AND item.UpdatedOnCurr <= @till AND @till < item.UpdatedOnNext
THEN 1
ELSE 0
END m
) m
WHERE item.Json IS NOT NULL AND (
(@from < item.UpdatedOnCurr AND item.UpdatedOnCurr <= @till AND @till < item.UpdatedOnNext)
OR (item.UpdatedOnCurr <= @from AND @from < item.UpdatedOnNext AND item.UpdatedOnNext <= @till)
);