I have a query with many tables and criteria and I'm trying to create a dynamic WHERE clause using COALESCE and Case statements. So far it's working well except in this case:
My main table is "Projects" and it is linked to the "Clients" table via a many-to-many table called "ProjectClients". In my criteria I have a parameter called @ClientKey (which I've set to NULL if it's not passed into the query) in which I pass the client key (or keys) that the user has selected in their criteria. The problem I'm running into is that if the user doesn't select a client as criteria, my WHERE clause is not including the projects in which there is no record in the ProjectClients table for that project (basically, no client(s) have been assigned to that project yet), so that project is not included in the result set. But I want to see all projects whether there's a client or not based on the absence of the client criteria. Here's the WHERE clause I have constructed so far:
Any ideas what I'm doing wrong?
My main table is "Projects" and it is linked to the "Clients" table via a many-to-many table called "ProjectClients". In my criteria I have a parameter called @ClientKey (which I've set to NULL if it's not passed into the query) in which I pass the client key (or keys) that the user has selected in their criteria. The problem I'm running into is that if the user doesn't select a client as criteria, my WHERE clause is not including the projects in which there is no record in the ProjectClients table for that project (basically, no client(s) have been assigned to that project yet), so that project is not included in the result set. But I want to see all projects whether there's a client or not based on the absence of the client criteria. Here's the WHERE clause I have constructed so far:
Code:
WHERE tAGProjects.ClosedProject = COALESCE(@OpenClosed, tAGProjects.ClosedProject)
AND tAGProjects.AGProjectKey = COALESCE(@AGProjectKey, tAGProjects.AGProjectKey)
AND tAGProjects.ProjectTitle LIKE COALESCE(@ProjectTitle, tAGProjects.ProjectTitle)
AND tClients.ClientNumber IN (CASE WHEN @ClientKey IS NULL THEN tClients.ClientNumber ELSE @ClientKey END)
Any ideas what I'm doing wrong?