开发者

How to use IF Statement or Case when in Where Clause SQL

Please help, how can I insert If or Case in Where clause

This is part of my code and I receive errors however I insert If or Case When.

This is the error Msg 156, Level 15, State 1, Procedure p5, Line 35

Incorrect syntax near the keyword 'BETWEEN'

AS 
WITH 
    t1 AS (SELECT 0 n UNION ALL SELECT 0 n UNION ALL SELECT 0 UNION ALL SELECT 0)
    ,Calendario AS (SELECT DATEADD(day, (ROW_NUMBER() OVER (ORDER BY a.n)), @CheckIn) AS Fetcha
        FROM t1 a, t1 b, t1 c, t1 d, t1 e, t1 f)    


SELECT @noches= convert(int,@Checkout - @CheckIn), @Sum = SUM(dbl*@canthabdbl),@SumSGL = SUM(SGL*@canthabsgl), @SumTPL = SUM(isnull(Triple,0)*@canthabtpl),@SumCUAD = SUM(isnull(Cuad,0)*@canthabcdpl),@SumChd = SUM(isnull(Chd,0)*@cantchd), @totalhab = (@Sum+@SumSGL+@SumTPL+@SumCUAD+@SumChd), @average = (@totalhab/@noches)  
FROM hotelsnew 
JOIN Calendario ON  
Calendario.Fetcha BETWEEN Desde AND Hasta+1

WHERE 
    CASE WHEN @checkout>hasta THEN  
    Calendario.Fetcha BETWEEN @CheckIn+1 AND @CheckOut-1  
    AND Hoteles = @IDHotel AND tipohabitacion = @IDTipo AND Id_plan = @IDPlan 
    ELSE 
    Calendario.Fetcha B开发者_如何学GoETWEEN @CheckIn AND @CheckOut  
    AND Hoteles = @IDHotel AND tipohabitacion = @IDTipo AND Id_plan = @IDPlan
    END  

RETURN 


Try this:

WHERE Calendario.Fetcha BETWEEN
    CASE WHEN @checkout>hasta THEN @CheckIn+1 ELSE @CheckIn END
    AND
    CASE WHEN @checkout>hasta THEN @CheckOut-1 ELSE @CheckOut END
    AND Hoteles = @IDHotel AND tipohabitacion = @IDTipo AND Id_plan = @IDPlan


Untested guess. See if this works.

WHERE 
(
   @checkout>hasta AND
   Calendario.Fetcha BETWEEN @CheckIn+1 AND @CheckOut-1 AND  
   Hoteles = @IDHotel AND tipohabitacion = @IDTipo AND Id_plan = @IDPlan 
) OR 
(
   @checkout <= hasta AND
   Calendario.Fetcha BETWEEN @CheckIn AND @CheckOut AND 
   Hoteles = @IDHotel AND tipohabitacion = @IDTipo AND Id_plan = @IDPlan
)


CASE statements typically go in the select part, like this:

SELECT 
  CASE ContactType WHEN 'Person' THEN LastName ELSE BusinessName END
FROM Contacts

For your WHERE clause, I would recommend rewriting it to be something like this:

WHERE 
    (@checkout>hasta AND Calendario.Fetcha BETWEEN @CheckIn+1 AND @CheckOut-1  
    AND Hoteles = @IDHotel AND tipohabitacion = @IDTipo AND Id_plan = @IDPlan)
    OR 
    (@checkout<=hasta AND Calendario.Fetcha BETWEEN @CheckIn AND @CheckOut  
    AND Hoteles = @IDHotel AND tipohabitacion = @IDTipo AND Id_plan = @IDPlan)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜