Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional WHERE Clauses in SQL Server 2008

Tags:

sql

sql-server

I am trying to execute a query on a table in my SQL Server 2008 database. I have a stored procedure that uses five int parameters. Currently, my parameters are defined as follows:

@memberType int,
@color int,
@preference int,
@groupNumber int,
@departmentNumber int

This procedure will be passed -1 or higher for each parameter. A value of -1 means that the WHERE clause should not consider that parameter in the join/clause. If the value of the parameter is greater than -1, I need to consider the value in my WHERE clause. I would prefer to NOT use an IF-ELSE statement because it seems sloppy for this case.

I saw this question here. However, it did not work for me. I think the reason why is because each of the columns in my table can have a NULL value. Someone pointed this scenario out in the fifth answer. That appears to be happening to me.

Is there a slick approach to my question? Or do I just need to brute force it (I hope not :().

Thank you!

like image 838
user336786 Avatar asked Jan 23 '26 02:01

user336786


1 Answers

I've done something like this in the past:

SELECT
  .....
FROM
  dbo.SOMETABLE AS T
WHERE
  (T.memberType = @memberType OR @memberType = -1)
  AND (T.color = @color OR @color = -1)
  AND (T.preference = @preference OR @preference = -1)
  AND (T.groupNumber = @groupNumber OR @groupNumber = -1)
  AND (T.departmentNumber = @departmentNumber OR @departmentNumber = -1)

Generally, however, my parameters that I don't care about are NULL. Then the query becomes:

SELECT
    .....
  FROM
    dbo.SOMETABLE AS T
  WHERE
    (T.memberType = @memberType OR @memberType IS NULL)
    AND (T.color = @color OR @color IS NULL)
    AND (T.preference = @preference OR @preference IS NULL)
    AND (T.groupNumber = @groupNumber OR @groupNumber IS NULL)
    AND (T.departmentNumber = @departmentNumber OR @departmentNumber IS NULL)
like image 53
BradBrening Avatar answered Jan 25 '26 20:01

BradBrening



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!