Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL ignore part of WHERE if parameter is null

I have a stored procedure that fetches info from a table based on 4 parameters.

I want to get values based on the parameters, but if a parameter is NULL then that parameter isn't checked. So if all 4 parameters is null I would show the entire table.

This is my SP (as you can see, this only works for 1 parameter atm):

CREATE PROCEDURE myProcedure     @Param1 nvarchar(50),     @Param2 nvarchar(50),     @Param3 nvarchar(50),     @Param4 nvarchar(50) AS BEGIN     IF(@Param1 IS NULL)         BEGIN             SELECT Id, col1, col2, col3, col4 FROM myTable         END     ELSE         BEGIN             SELECT Id, col1, col2, col3, col4 FROM myTable WHERE col1 LIKE @Param1+'%'         END END 

Is there some way to do this without having a IF for every possible combination (15 IFs)?

like image 827
Johan Hjalmarsson Avatar asked Jul 25 '13 06:07

Johan Hjalmarsson


People also ask

How do you ignore NULL values in SQL query?

SELECT column_names FROM table_name WHERE column_name IS NOT NULL; Query: SELECT * FROM Student WHERE Name IS NOT NULL AND Department IS NOT NULL AND Roll_No IS NOT NULL; To exclude the null values from all the columns we used AND operator.

How do you check if a parameter is empty or NULL in SQL Server?

Inside the stored procedure, the parameter value is first tested for Null using the ISNULL function and then checked whether it is Blank (Empty). If the parameter has value then only matching records will be returned, while if the parameter is Null or Blank (Empty) then all records from the table will be returned.

Can we use coalesce in WHERE clause?

Because the COALESCE is an expression, you can use it in any clause that accepts an expression such as SELECT , WHERE , GROUP BY , and HAVING .

Can we use Isnull in WHERE clause?

We use IS NULL to identify NULL values in a table. For example, if we want to identify records in the employee table with NULL values in the Salary column, we can use IS NULL in where clause. WHERE EmployeeSalary IS NULL; In the following screenshot, we cannot use SQL Server ISNULL to find NULL values.


1 Answers

How about something like

SELECT Id, col1, col2, col3, col4  FROM    myTable  WHERE   col1 LIKE @Param1+'%' OR      @Param1 IS NULL 

in this specific case you could have also used

SELECT Id, col1, col2, col3, col4  FROM    myTable  WHERE   col1 LIKE ISNULL(@Param1,'')+'%' 

But in general you can try something like

SELECT Id, col1, col2, col3, col4  FROM    myTable  WHERE   (condition1 OR @Param1 IS NULL) AND     (condition2 OR @Param2 IS NULL) AND     (condition3 OR @Param3 IS NULL) ... AND     (conditionN OR @ParamN IS NULL) 
like image 198
Adriaan Stander Avatar answered Oct 08 '22 19:10

Adriaan Stander