I am trying to filter a single table (master) by the values in multiple other tables (filter1, filter2, filter3 … filterN) using only joins.
I want the following rules to apply:
(A) If one or more rows exist in a filter table, then include only those rows from the master that match the values in the filter table.
(B) If no rows exist in a filter table, then ignore it and return all the rows from the master table.
(C) This solution should work for N filter tables in combination.
(D) Static SQL using JOIN syntax only, no Dynamic SQL.
I’m really trying to get rid of dynamic SQL wherever possible, and this is one of those places I truly think it’s possible, but just can’t quite figure it out. Note: I have solved this using Dynamic SQL already, and it was fairly easy, but not particularly efficient or elegant.
What I have tried:
-
Various INNER JOINS between master and filter tables – works for (A) but fails on (B) because the join removes all records from the master (left) side when the filter (right) side has no rows.
-
LEFT JOINS – Always returns all records from the master (left) side. This fails (A) when some filter tables have records and some do not.
What I really need:
It seems like what I need is to be able to INNER JOIN on each filter table that has 1 or more rows and LEFT JOIN (or not JOIN at all) on each filter table that is empty.
My question: How would I accomplish this without resorting to Dynamic SQL?
In SQL Server 2005+ you could try this:
My understanding is, filter tables without any matches simply must not affect the resulting set. The output should only consist of those
masterdatarows that have matched all the filters where matches have taken place.