简体   繁体   中英

Apply filter on sql query conditionally

Lets say I have a parameter @Name in a Stored Procedure. I want to filter by this parameter only if it is not empty / null. In any other case I want to ignore the filter.

I came up with the following two solutions. For the sake of example let us consider only the case that parameter is empty.

select *
  from MyTable
 where (len(rtrim(ltrim(@Name))) > 0 and Name = @Name) or (len(rtrim(ltrim(@Name))) = 0)

and the second one

@query = 'select * from MyTable'
if (len(rtrim(ltrim(@Name))) > 0)
    @query = @query + ' Name = @Name '    

Both of the approaches are working as expected.

  • Which do you think is the most clean (in terms of code) and easily maintainable
  • Are there any other (better) alternatives.

Note: This question may also suit in Code Review, please comment if you think so, in order to migrate there

It can be simplified like this

select *
  from MyTable
 where  Name = @Name or @Name = '' or @Name is null

or as mentioned in comments, use NULLIF to check for empty string then replace it with NULL then validate it against IS NULL

where (Name = @Name or nullif(@Name, '') is null)

You don't need to check for length, by default, sql server is trailing-spaces-sensitive (The only exception to this rule is when the right side of the LIKE predicate's expression contains trailing spaces, then the pad is not removed).

Take the code below.

DECLARE @Name='              '

IF(@Name='') SELECT 1 ELSE SELECT 0

If you run the above code above you will get a result of 1. In your case, you can drop the LTRIM and RTRIM and simply test for equality against an empty string literal.

select *
  from MyTable
  where ((@Name='' OR @Name IS NULL)OR(Name = @Name))

OR

IF(@Name='') SET @Name=NULL

select *
      from MyTable
      where (@Name IS NULL OR Name = @Name)

if you are working with dynamic sql in stored procedure try something like this . It is better to use different variables for main select query and dynamic where query which can be extended easily . using this approach it will be easy to maintain when you proc becomes lengthy.

    declare @finalquery varchar(max)
    declare @mainSelectquery nvarchar(500);
    declare @whereCondtions varchar (1000);
    declare @DateParam datetime
    set @mainSelectquery=''
    set @whereCondtions =''

    set @finalquery =''

    set @DateParam=getdate()
    set @mainSelectquery = 'select * from tblOrders  where 1=1  '

    set @whereCondtions =  ' and Order_site =''TSN'''

    set @whereCondtions = @whereCondtions + ' AND CAST(ORDER_APPROVED_DATE_LT AS DATE)=CAST(GETDATE() AS DATE)' 

    set @finalquery =( @mainSelectquery + @whereCondtions)

    print @finalquery

 ---- You can further extend this by adding more where condition based on the parameter pass in stored proc 
 if (@OrderID !=0)
 begin 
 set @whereCondtions =  ' OrderID='+str ( @stateRefID )
 end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM