I have a table with columns [From], [To]
. I need to select these columns as a single list and I do it this way:
SELECT [From] FROM [TableX] WHERE (...)
UNION
SELECT [To] FROM [TableX] WHERE (...)
The problem is that I don't want to duplicate WHERE (...)
condition as it's quite long. Is there a way to avoid this duplication?
Use a CTE to prevent duplicating your WHERE
condition:
;WITH [CTE_Criteria] AS (
SELECT [From], [To]
FROM [TableX]
WHERE (...)
)
SELECT [From] FROM [CTE_Criteria]
UNION
SELECT [To] FROM [CTE_Criteria];
Do the UNION
in a derived table, and have one common WHERE
clause.
select *
from
(
SELECT [From] FROM [TableX]
UNION
SELECT [To] FROM [TableX]
)
WHERE (...)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.