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 2005 Forums
 Transact-SQL (2005)
 query with if else in it

Author  Topic 

bill_
Starting Member

38 Posts

Posted - 2010-05-19 : 11:58:23
Hope I can explain this ok.

I need to write a query with a where clause that varies depending on a parameter existing or not.
For example if a birthdate of '01/01/01' is passed as a parameter, then I need to only get rows with DOBs of '01/01/01' otherwise I should not filter on DOB at all.

Trying a WHERE like this with no luck.

WHERE CONDITION1 AND CONDITION2 AND
IF LEN(@PARAM_DOB)>0
@PARAM_DOB=DOB
ELSE
0=0

1. How is this done right ?
2. I will need to put subqueries in conditionally later, any advice would be appreciated.

jimf
Master Smack Fu Yak Hacker

2875 Posts

Posted - 2010-05-19 : 12:35:55
If the parameter is passed in as null you can do something like

WHERE DOB like isnull(@PARAM_DOB,'%')
or alternatively
DOB = @PARAM_DOB or (@PARAM_DOB is null and DOB like '%')

Jim



Everyday I learn something that somebody else already knew
Go to Top of Page
   

- Advertisement -