I have a table Tran with transaction records.
I have two tables, Parameters1 and Parameters2, which are used to filter results when selecting from the Tran table a la:
SELECT *
FROM
Tran t JOIN
Parameters1 p1 ON T.code1 = p1.code1
Parameters2 p2 ON T.code2 = p2.code2
WHERE p1.code1 is not null AND
p2.code2 is not null
Sometimes Parameters1 or Parameters2 is empty.
What I want is for the filtering to happen only if the Parameters tables have records. In other words, if Parameters1 is empty, don’t use it to filter, and vice versa. Same goes for Parameters2.
I’m stumped.
You’d normally do this using dynamic SQL, since coding up dynamic search conditions with static SQL is generally hackish. If you are interested in this approach I highly recommend Erland Sommarskog’s page on dynamic SQL for SQL Server 2005. He has a great case study with plenty of example code on how to do exactly what you’re asking for.
1. Setup
Whether you use dynamic or static SQL, you should first determine upfront what filters apply:
2.a. Dynamic SQL
If you’re going the dynamic SQL route you’d then do:
2.b.i. Static SQL: Sub-SELECTs in the WHERE clause
Otherwise, you’d continue with this ugly (and probably poorly performing) static SQL:
Erland also presents static SQL approaches like this one on that same page I referred to earlier. You may find a better approach there.
2.b.ii. Static SQL: LEFT OUTER JOIN
You can also go with this approach, which you proposed in the comments on this answer: