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)
 Where claues with optional values

Author  Topic 

san3297
Starting Member

7 Posts

Posted - 2010-11-04 : 13:36:36
ID SIZE NO Value
NULL NULL NULL 11467.760
NULL NULL NULL 1033.430
NULL 2 Blank 1141.860
1 NULL NULL 8.000


I have the table data as specified above. I am building a stored proc where i have a where claue for id, size and number. When the where clause parameters are blank or null it should send me all rows.

Suppose @ID=Null @Size=Null @N0=Null it should return all the four rows. If @ID=Null @Size=2 @No=Null or Blank it should return 3rd Row. How can i format the where claues for this.

I created query as

Select * from table where (ID= @ID or ID= null) and (SIZE= @Size or SIZE= null) and (NO= @NO or NO= null)

But it returns me no rows for any value i passs.

Sachin.Nand

2937 Posts

Posted - 2010-11-04 : 13:58:52
Select * from table where (ID= @ID or @ID Is Null) and (SIZE= @Size or @SIZE Is Null) and (NO= @NO or @N0 Is Null)

PBUH

Go to Top of Page

GilaMonster
Master Smack Fu Yak Hacker

4507 Posts

Posted - 2010-11-04 : 14:39:02
Those kind of (Variable IS NULL Or Column = Variable) queries typically perform very badly. It's one of those patterns that looks just soooo useful but fails so badly in reality.

http://sqlinthewild.co.za/index.php/2009/03/19/catch-all-queries/

--
Gail Shaw
SQL Server MVP
Go to Top of Page
   

- Advertisement -