This query filters some IDs from a master table, and returns all data abpout that IDs from two other tables as two record sets:
WITH filteredIds (fid) AS
(
SELECT id
FROM MasterTable
WHERE <somecondition>
)
SELECT *
FROM Table1
RIGHT JOIN filteredIds ON (Table1.id = filteredIds.fid);
WITH filteredIds (fid) AS
(
SELECT id
FROM MasterTable
WHERE <somecondition>
)
SELECT *
FROM Table2
RIGHT JOIN filteredIds ON (Table2.id = filteredIds.fid);
This works so far, but it would be great to have just one WITH clause, since the condition is always the same. Further more, the condition is often written manually, since this is used to collect some diagnostics data.
But this
WITH filteredIds (fid) AS
(
SELECT id
FROM MasterTable
WHERE <somecondition>
)
SELECT *
FROM Table1
RIGHT JOIN filteredIds ON (Table1.id = filteredIds.fid);
SELECT *
FROM Table2
RIGHT JOIN filteredIds ON (Table2.id = filteredIds.fid);
does not work, SQL Server claims it does not know object filteredIds in the last query.
Have I overseen something, or doesn't it work that way? I guess the alternative would be a temporary table.