Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignoring a NULL parameter in T-SQL

Tags:

I want to be able to pass in a list of parameters, and ignore the ones which are NULL. So that the query is in effect pretending that the filter isn't there and ignoring it.

I was doing it like this:

(@thing IS NULL or Thing=@thing)  

Is this right, and if so, would it perform badly? It's seems to be a lot slower than constructing the SQL separately.

What's the optimal way to do this?

FIXED! See Marc Gravell's answer. In summary using IS NULL many times is a big performance hit.

like image 748
Damien Avatar asked Feb 10 '09 14:02

Damien


People also ask

Which function does not ignore NULL values SQL?

COUNT(1) and COUNT(*) are completely interchangeable and both yield same results – both do NOT ignore NULL values and both return the number of rows of a particular table. It counts all the duplicate values (number 5 repeats two times) and based on results, SQL server counts both observations.

How do you return all records if parameter is NULL?

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.

Is NULL parameter in SQL?

If you want a parameter that can filter by a certain value, but when you have no value in your parameter, SQL returns no results. When the parameter has no value, SQL interprets it as null in your code. Null means no value. You can fix this problem by adding a code to fix the null case.


1 Answers

Once you get more than a couple of these, then yes: it starts to get pretty slow. In such cases, I tend to use generated TSQL - i.e.

DECLARE @sql nvarchar(4000) SET @sql = /* core query */  IF @name IS NOT NULL     SET @sql = @sql + ' AND foo.Name = @name'  IF @dob IS NOT NULL     SET @sql = @sql + ' AND foo.DOB = @dob'  // etc  EXEC sp_ExecuteSQL @sql, N'@name varchar(100), @dob datetime',         @name, @dob 

etc

Note that sp_ExecuteSQL caches query-plans, so any queries with the same args can potentially re-use the plan.

The downside is that unless you sign the SPROC, the caller needs SELECT permissions on the table (not just EXEC permissions on the SPROC).

like image 59
Marc Gravell Avatar answered Oct 10 '22 06:10

Marc Gravell