I have an SQL Server query that uses some CTEs (Common Table Expressions). It has two tables that it selects the data from. The two tables are identical in structure, but not necessary data. The query will first select from table_a
and if no rows are fetched, it then selects from table_b
. The query is something like this:
;WITH cte_a AS (
...
), cte_b AS (
...
)
SELECT *
FROM table_a
INNER JOIN cte_a ON condition_a
OR NOT EXISTS (
SELECT *
FROM table_b
INNER JOIN cte_b ON condition_b
)
The current problem that I have is that cte_b
will always be executed regardless of whether table_a
returns any rows. This is not very ideal for me; I would like to have cte_b
execute if and only if the subquery for table_a
returns no rows.
I tried moving the cte_b
to be just before the subquery for table_b
as
;WITH cte_a AS (
...
)
SELECT *
FROM table_a
INNER JOIN cte_a ON condition_a
OR NOT EXISTS (
;WITH cte_b AS (
...
)
SELECT *
FROM table_b
INNER JOIN cte_b ON condition_b
)
However, the IDE complains. I think that this wasn't the way CTEs are supposed to be used.