Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL server conditional select statement

Ok, this might be an easy one, but I just can't get it.

I am creating a page which will query a table with many columns and most items are not unique. I need to be able to get a list of records that match as many of the (up to 4) search criteria as possible.

Example:

I am user searching for the following items, I enter at least one and up to 4 of the items below in a text box: Name, age, gender, weight (user may or may not fill in all of them).

If he just enters "F" for gender, then he will get a list of thousands of females with their name, age, gender and weight.

However if he enters "F" for gender and "300" for weight, he will get a much smaller list of returned records.

I need to be able to create a sql statement that can perform that search with that functionality.

advTHANKSance

like image 741
eviljack Avatar asked May 18 '26 09:05

eviljack


1 Answers

I've used similar to the one below to do what you are trying:

DECLARE @Gender varchar(1)
DECLARE @Age int
DECLARE @Weight int
DECLARE @Name varchar(64)

 SELECT * FROM MyTable
    WHERE
    (@Gender is null OR Gender = @gender)
    AND (@weight is null OR Weight = @weight)
    AND (@Age is null OR  age = @Age)
    and (@Name is null OR Name = @Name)

if you were to create a stored procedure (which i would recommend) it would look like this:

CREATE PROCEDURE SelectRecords
    @Gender varchar(1),
    @Age int,
    @Weight int,
    @Name varchar(64)
AS
     SELECT * FROM MyTable
        WHERE
        (@Gender is null OR Gender = @gender)
        AND (@weight is null OR Weight = @weight)
        AND (@Age is null OR  age = @Age)
        and (@Name is null OR Name = @Name)

What this stored procedure is doing is checking to see if you passed a value in for the specific parameter. If you DID NOT then it will be null and the condition will be true. if you DID then it will not be null and the second condition must evaluate to true for the record to be returned.

like image 64
Abe Miessler Avatar answered May 19 '26 23:05

Abe Miessler