2011-09-23 157 views
1

請幫幫忙,我怎麼能在Where條款如何使用IF語句或案例時,WHERE子句中SQL

這是我的代碼的一部分,我收到錯誤,但是我插入IfCase When插入IfCase

這是錯誤消息156,級別15,狀態1,過程P5,35號線

關鍵字附近有語法錯誤 '之間'

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 = (@[email protected][email protected][email protected][email protected]), @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 BETWEEN @CheckIn AND @CheckOut 
    AND Hoteles = @IDHotel AND tipohabitacion = @IDTipo AND Id_plan = @IDPlan 
    END 

RETURN 
+0

確實看起來像t-sql –

回答

2

嘗試這個:

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 
+0

哦,這比我的回答更優雅。我假設它適用於+1:D –

2

未經檢驗的猜測。看看這是否有效。

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 
) 
1

CASE語句通常在選擇部分走,像這樣:

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

爲了您的WHERE子句,我會建議重寫它是這樣的:

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)