Skipping WHERE statement if the variable for that statement is null

后端 未结 2 413
甜味超标
甜味超标 2021-01-24 05:56

I will have a table

TABLE1
ID  Name   Country
1   Anna   Singapore
2   Brad   UK
3   Cassie US

declare @place varchar(20);
set @place=\'US\';

select * from Tab         


        
相关标签:
2条回答
  • 2021-01-24 06:38

    For this simple case in your question just use

    IF ( @place IS NULL )
      SELECT *
      FROM   table1
    ELSE
      SELECT *
      FROM   table1
      WHERE  country = @place  
    

    If your actual situation is more complex you could use

    select * 
    from Table1 
    where @place is null or country=@place 
    option (recompile)
    

    The reason for needing the recompile hint is to avoid having a single plan catering for both cases and doing an unnecessary scan in the event that you do supply an explicit value.

    These, and other alternatives such as generating the query dynamically, are discussed in detail in the article Dynamic Search Conditions in T-SQL

    0 讨论(0)
  • 2021-01-24 06:52

    like and = are equivalent in your situation because you are dealing with text (char, nchar, varchar, nvarchar) values.

    Instead of

    WHERE  country = @place  
    

    try

    WHERE  country like @place  
    

    For the variable set try Instead of

    set @place='US'
    

    Try

    set @country = isnull('''US''','''%''')
    

    To test this:

    declare @country nvarchar(50)
    set @country = isnull('''US''','''%''')
    print @Country
    set @country = isnull(NULL,'''%''')
    print @Country
    

    The extra quotes are necessary because in your example you are using explicit values - ' is an escape character and you need a single quote around each value to signify it is NOT a table column. If you were using the COLUMN_NAME you would simply use a single quote around the % character.

    Depending on your SQL version you may have to use a different wildcard character. This is fairly a fairly direct and linear solution, although there are risks associated with open variables.

    0 讨论(0)
提交回复
热议问题