我有一个包含[From], [To]
列的表格。我需要选择这些列作为单个列表,我这样做:
SELECT [From] FROM [TableX] WHERE (...)
UNION
SELECT [To] FROM [TableX] WHERE (...)
问题在于我不想复制WHERE (...)
条件,因为它很长。有没有办法避免这种重复?
答案 0 :(得分:3)
使用CTE防止重复WHERE
条件:
;WITH [CTE_Criteria] AS (
SELECT [From], [To]
FROM [TableX]
WHERE (...)
)
SELECT [From] FROM [CTE_Criteria]
UNION
SELECT [To] FROM [CTE_Criteria];
答案 1 :(得分:1)
在派生表中执行UNION
,并且有一个共同的WHERE
子句。
select *
from
(
SELECT [From] FROM [TableX]
UNION
SELECT [To] FROM [TableX]
)
WHERE (...)