How to use If Statement in Where Clause in SQL?

后端 未结 4 443
抹茶落季
抹茶落季 2020-12-17 16:12

I need to use if statement inside where clause in sql.

Select * from Customer
WHERE  (I.IsClose=@ISClose OR @ISClose is NULL)  
AND    
(C.FirstName like \'%         


        
相关标签:
4条回答
  • 2020-12-17 16:37

    Nto sure which RDBMS you are using, but if it is SQL Server you could look at rather using a CASE statement

    Evaluates a list of conditions and returns one of multiple possible result expressions.

    The CASE expression has two formats:

    The simple CASE expression compares an expression to a set of simple expressions to determine the result.

    The searched CASE expression evaluates a set of Boolean expressions to determine the result.

    Both formats support an optional ELSE argument.

    0 讨论(0)
  • 2020-12-17 16:42

    You have to use CASE Statement/Expression

    Select * from Customer
    WHERE  (I.IsClose=@ISClose OR @ISClose is NULL)  
    AND    
        (C.FirstName like '%'+@ClientName+'%' or @ClientName is NULL )    
    AND 
         CASE @Value
             WHEN 2 THEN (CASE I.RecurringCharge WHEN @Total or @Total is NULL) 
             WHEN 3 THEN (CASE WHEN I.RecurringCharge like 
                                   '%'+cast(@Total as varchar(50))+'%' 
                         or @Total is NULL )
         END
    
    0 讨论(0)
  • 2020-12-17 16:44
    SELECT *
      FROM Customer
     WHERE (I.IsClose=@ISClose OR @ISClose is NULL)  
       AND (C.FirstName like '%'+@ClientName+'%' or @ClientName is NULL )    
       AND (isnull(@Value,1) <> 2
            OR I.RecurringCharge = @Total
            OR @Total is NULL )    
       AND (isnull(@Value,2) <> 3
            OR I.RecurringCharge like '%'+cast(@Total as varchar(50))+'%'
            OR @Total is NULL )
    

    Basically, your condition was

    if (@Value=2)
       TEST FOR => (I.RecurringCharge=@Total  or @Total is NULL )    
    

    flipped around,

    AND (isnull(@Value,1) <> 2                -- A
            OR I.RecurringCharge = @Total    -- B
            OR @Total is NULL )              -- C
    

    When (A) is true, i.e. @Value is not 2, [A or B or C] will become TRUE regardless of B and C results. B and C are in reality only checked when @Value = 2, which is the original intention.

    0 讨论(0)
  • 2020-12-17 17:00
    select * from xyz where (1=(CASE WHEN @AnnualFeeType = 'All' THEN 1 ELSE 0 END) OR AnnualFeeType = @AnnualFeeType)
    
    0 讨论(0)
提交回复
热议问题