Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 Dynamic WHERE clause in SELECT satment?

Author  Topic 

Eagle_f90
Constraint Violating Yak Guru

424 Posts

Posted - 2013-06-21 : 14:27:40
I have a SELECT statement with 2 conditions in the WHERE clause and I want 1 of those conditions to be optional as the value may or may not be passed in by the calling application. Doing some goggling I found this solution:

WHERE di.InventoryDate BETWEEN @SDate AND @EDate
AND di.JDELocation = @JDELocation OR @JDELocation IS NULL


Which works, sort of. As long as the JDELocation is passed in the results returned will always be between the Sdate and EDate but if the JDELocation is not passed in by the calling app then the date constraint is ignored. How can I modify this so that even if the JDELocation is not passed in the date constraint is still followed?

--
If I get used to envying others...
Those things about my self I pride will slowly fade away.
-Stellvia

TG
Master Smack Fu Yak Hacker

6065 Posts

Posted - 2013-06-21 : 14:29:50
WHERE di.InventoryDate BETWEEN @SDate AND @EDate
AND (di.JDELocation = @JDELocation OR @JDELocation IS NULL)

Be One with the Optimizer
TG
Go to Top of Page

Eagle_f90
Constraint Violating Yak Guru

424 Posts

Posted - 2013-06-21 : 14:33:11
Thanks, that worked perfectly

--
If I get used to envying others...
Those things about my self I pride will slowly fade away.
-Stellvia
Go to Top of Page

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2013-06-21 : 14:33:43
http://sqlinthewild.co.za/index.php/2009/03/19/catch-all-queries/
Go to Top of Page
   

- Advertisement -