Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL Case in where statement if parameter is null

I have a SP that gives me a lot of hard times.

The sp gets a two parameters @madeByUserId and @reportedByUserId. I want to have something like:

 select * from table
  where MadeByUserId = @madeByUserId (if(@reportedByUserID != null) and ReportedByUserID = @reportedByUserID)

Basically I want to make a case in the where clause to include another filter condition based of the null/not null state of the @reportedByUserId

Is that possible?

Thanks a lot, Radu

like image 664
Radu D Avatar asked Dec 08 '10 08:12

Radu D


People also ask

Can I use is null with WHERE clause?

Null values can be used as a condition in the WHERE and HAVING clauses. For example, a WHERE clause can specify a column that, for some rows, contains a null value. A basic comparison predicate using a column that contains null values does not select a row that has a null value for the column.

Is null in WHERE condition in SQL Server?

Let's look at how to use the IS NULL condition in a SELECT statement in SQL Server. For example: SELECT * FROM employees WHERE last_name IS NULL; This SQL Server IS NULL example will return all records from the employees table where the last_name contains a null value.

Can we use null in case statement SQL?

You cannot use simple case to test for null because it always uses the equals operator ( = ). That is because the condition null = null is not true5—consequently, a when null clause never applies. If the <common operand> is null , the else clause applies.

Can case statement be used in WHERE clause?

CASE can be used in any statement or clause that allows a valid expression. For example, you can use CASE in statements such as SELECT, UPDATE, DELETE and SET, and in clauses such as select_list, IN, WHERE, ORDER BY, and HAVING.


1 Answers

You could use COALESCE.

SELECT  * 
FROM    Table
WHERE   MadeByUserId = @madeByUserId 
        AND ReportedByUserID = COALESCE(@reportedByUserID, ReportedByUserID)

This translates to

 if @reportedByUserID is `NOT NULL` then 
   compare ReportedByUserID with @reportedByUserID
 else
   compare ReportedByUserID with ReportedByUserID

From MSDN

COALESCE

Returns the first nonnull expression among its arguments.

like image 87
Lieven Keersmaekers Avatar answered Sep 28 '22 01:09

Lieven Keersmaekers