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
 General SQL Server Forums
 New to SQL Server Programming
 where condition if value exists in select query

Author  Topic 

subhaoviya
Posting Yak Master

135 Posts

Posted - 2011-11-21 : 11:07:55
HI,

i am having sp which has 3 input parameters @var1 int,@var2 string, @var3 int.
need to form a select query like if all the three variable value exists

select * from table1 where col1=@var1 and col2=@var2 and col3=@var3

if @var2 is null then
select * from table1 where col1=@var1 and col3=@var3

how to make this simple?

thanks
subha


visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-11-21 : 11:13:30
depending on which all parameters can be null you can make it like

select * from table1
where (col1=@var1 or @var1 is null)
and (col2=@var2 or @var2 is null)
and (col3=@var3 or @var3 is null)


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2011-11-21 : 11:37:39
If you have optional parameters (catch-all query), this link might be usefull:
http://sqlinthewild.co.za/index.php/2009/03/19/catch-all-queries/
Go to Top of Page
   

- Advertisement -