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 2008 Forums
 Transact-SQL (2008)
 Query Help for paramters when null?

Author  Topic 

akpaga
Constraint Violating Yak Guru

331 Posts

Posted - 2013-10-21 : 16:17:27
Hi friends,

I have a query in the following way

select * from Customer
where CustmerNumber=@CustomerNumber
and Date_Customer=@date_Customer

But the problem i have is to return all records when the parameters are null and return records even if one parameter is passed like only customerNumber is defined but not Date_customer and vice versa...

How can i achiove this...Thank you

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2013-10-21 : 16:31:40
The term for that sort of query is a catch-all query. There are several ways to write them. Here is one:
select * from Customer
where
(CustmerNumber=@CustomerNumber or @CustomerNumber IS NULL)
and (Date_Customer=@date_Customer or @date_Customer IS NULL)
Here is a link that gives more detail on these types of queries:
http://sqlinthewild.co.za/index.php/2009/03/19/catch-all-queries/
Go to Top of Page

akpaga
Constraint Violating Yak Guru

331 Posts

Posted - 2013-10-21 : 17:12:30
thank you lamprey..works good.
Go to Top of Page
   

- Advertisement -