Question

I am using SQL 2008R2. I have a stored procedure that has 56 optional parameters. It is used by a front-end application to search a table. Many columns contain NULL or empty string. When the application is passing '%' as value for one parameter the sproc returns rows matching all non-null values for the column. The requirement is to return all non-null and NULL matching rows (i.e. All rows). To simulate it I have this little example code:

-- table
declare @foobar table
(
column1 nvarchar(100)
, column2 nvarchar(100)
)

-- dummy data
insert into @foobar(column1, column2)
select '100', 'high' union
select '200', 'low' union
select '300', null union
select '400', 'medium' union
select '500', '' union
select '600', 'high' union
select '700', '' union
select '800', null

-- parameter
declare @column2 nvarchar(100)
set @column2 = '%'

-- This returns all non-null values.  
-- Requirement is to return all non-null and NULL values.
select column1, column2 from @foobar 
where (column2 like @column2 + '%' or nullif(@column2, '') is null)

/*

'%' returns all records where value is not null
Problem: Dev requires all values including null ones.
Thought about the followings:
1. Do a dynamic SQL based query and use sp_executesql:

    -- create the WHERE clause
    if @Column2 = '%'
    @WHERE = 'AND (column2 like @column2 OR column is null)'
    else
    @WHERE = 'AND column2 like @column2 OR nullif(@column2, '') is null)'
**/

I dislike dynamic queries (I am just lazy). However, for this I have been trying dynamic query and sp_executesql. I am not sure if it is possible to create dynamic query for this with 56 parameters where many parameters will be null (nothing supplied from the front-end). I am just wondering if there is a better way of doing this without using dynamic query.

Was it helpful?

Solution

You just need minor change to your where clause.

First part before OR will find any non null values.

Second Part will look for null values only when user inputed %

(column2 like @column2 + '%' or (@column2 = '%' and column2 is null))

OTHER TIPS

How about

WHERE (column2 LIKE @column2 + '%' OR @column2 = '%')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top