views:

107

answers:

3

Hello everyone, I have a table Student with 2 fields:

Name: nvarchar(256)
Age: int

User will use a WinForm application to input a Name and a Age for searching.

  • If inputted Name is empty, sql will not query Name field.
  • If inputted Age is 0, sql will not query Age field.
  • If Name is Null and inputted Name is empty -> record is matched. If Name is Null and inputted Name is not empty -> record is not matched. And also similar for Age field.

My problem is that how to write a sql like this.

P/S: I use SQL Server 2005.

Please help me. Thanks.

+3  A: 

One approach is to make the parameters nullable and use this pattern:

Create Procedure MyTest
(
    @param1 int = NULL,
    @param2 varchar = NULL 
)
AS
BEGIN

SELECT Blah...
FROM Table
WHERE
    ((@param1 IS NULL) OR (somecolumn = @param1)) AND
    ((@param2 IS NULL) OR (someothercolumn = @param2))


END

[Note: it can have parameter sniffing side effects, if there are many parameters...]

Mitch Wheat
+1  A: 
select * from thetable
where (@name='' or [name]=@name) and (@age=0 or age=@age)

However, the above query forces table scan. For better performance and more complex scenario (I guess you simplified the question in you original post), consider use dynamic sql. By the way, Linq to SQL can help you build dynamic SQL very easily, like the following:

IQueryable<Person> persons = db.Persons;
if (!string.IsNullOrEmpty(name)) persons = persons.Where(p=>p.Name==name);
if (age != 0) persons = persons.Where(p=>p.Age=age);
Codism
The query should not force a table scan to start with. Also note that '' and 0 are not identical to NULL.
TomTom
A: 

I would use dynamic SQL, building the WHERE clause with a variable number of terms based on the inputs.

I answered questions for very similar cases recently. See those answers for examples:

Those questions were about PHP, but the technique can be adapted to any programming language.

Bill Karwin