Click here to Skip to main content
15,887,936 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I have 4 variables coming into a stored procedure from c#. i must pass all the variables. This variables can either have a value or be null.

If the particular variable is null, I need to select all the rows in the table (some with NULL values, some with actual data).

If the variable is not null, I only need to select the rows where the variable matches a column.
i tried giving

SQL
SELECT FirstName FROM AdmissionTbl WHERE (City=@city or City is null) and (state=@state or state is null) and (religion=@religion or religion is null)and (marks=@marks or marks is null)


if a value is passed it works, but if it is null it is not retrieving all the records.
Can anyone helpme?
Posted
Updated 15-Feb-13 19:35pm
v2
Comments
demouser743 16-Feb-13 1:37am    
Will all the values be null or particular values or null
sukumari1 16-Feb-13 1:56am    
based on user selection; values may or may not be null

Quote:
i tried giving
SELECT FirstName FROM AdmissionTbl WHERE (City=@city or City is null) and (state=@state or state is null) and (religion=@religion or religion is null)and (marks=@marks or marks is null)

you are almost correct but a small change
SQL
SELECT FirstName FROM AdmissionTbl 
WHERE (@city is null or City=@city) 
and (@state is null or state=@state) 
and (@religion is null or religion=@religion) 
and (@marks is null or marks=@marks)

Hope it helps you!
 
Share this answer
 
Hi check here I don't know how you build your table I have create a table with ID, Firstname,city and retrieving all firstname when city is matched or city is null

SQL
CREATE TABLE [dbo].[tblDemo]([id] [int] NOT NULL,[FirstName] [varchar](50) NULL,
[City] [varchar](50) NULL) ON [PRIMARY]


http://s8.postimage.org/4oukaxwtx/sql.jpg[^]


this is my query to retrieve the firstname when city is null or value is passed
SQL
Select FirstName From tbldemo Where city is null or city like 'RJY'


http://s4.postimage.org/e4qlni62l/results.jpg[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900