Reputation: 3101
I have a table name Students having (studentId, StudentName,Address,PhoneNo)
i have provided a filter for user to select only StudentId from Combobox to get the details of Students... and generate Report.
I have written following Query to get student Detail :
(select * from Students where StudentId = stdId)
Here stdId is a Parameter that i pass from code
It works fine if i select single studentId.... But in user selection Comobobox i have also provided "ALL"
if user Select All
from combobox i want to display details of all student
So what should I pass in stdId
if user selects All
?
I used inline Query in C# (not using SQL Stored Procedure)
Upvotes: 5
Views: 214
Reputation: 2624
You can do it like this .
SELECT * from Students s
WHERE s.studentId = ISNULL(@StudentId,s.studentId)
When "All" is selected in combo box pass null in your @studentid parameter. If you can not pass null in parameter then pass -1 or anything which can not be contain in you combox option and do it like this:(if -1= All)
SELECT * from Students s
WHERE s.studentId = @StudentId or @StudentId=-1
You can also try the answer given by Curt.
Upvotes: 6
Reputation: 266
If the where clause is included in the query you also need to supply a valid parameter value and it is therefore not possible to get all students when the where clause is included.
You need to differentiate your query based on the value selected in the combobox. You can do something like the following.
int studentId = 0;
//Where selectedValue comes from your combobox
Int32.TryParse(selectedValue, out studentId);
var query = "select * from Students";
if (studentId > 0)
{
query = query + " where StudentId = @StudentId";
//Remember to add studentId as parameter value
}
Upvotes: 1
Reputation: 10680
In your stored procedure header, change the definition of @StudentId so that it can be passed as NULL.
ALTER PROCEDURE dbo.WhateverYourProcedureIsCalled( @StudentId int = null )
Then change your WHERE clause as follows
...
SELECT * from Students
WHERE @StudentId IS NULL OR StudentId = @StudentId
From your code, if ALL is passed, you can omit the part where you set the value of the @StudentId parameter. SQL Server will use the default if not passed.
Upvotes: 4
Reputation: 103338
If user selects all, pass NULL
to @StudentId
and change your query to:
select *
from Students
where (StudentId=@StudentId OR @StudentId IS NULL)
Upvotes: 6