SQL IF不如THERE子句中的大小

时间:2016-03-05 15:34:03

标签: sql case iif

我想在WHERE中使用CASE,或者使用agregat函数IIF或其他类似的东西:

@iKapacitet
AS
SELECT ID, Name
FROM Private-Accommodation
WHERE [Private-Accommodation].[Otok]='Rab'AND 
IIF(@iKapacitet = 1,[Private-Accommodation].[maxPersons] < 3,
IIF(@iKapacitet = 2, [Private-Accommodation].[maxPersons] < 3 AND [Private-Accommodation].[maxPersons] > 5, 
[Private-Accommodation].[maxPersons] BETWEEN 4 AND 6))
ORDER BY [Private-Accommodation].[RedniBr]

如果使用CASE更容易:

CASE @iKapacitet 
WHEN 1 THEN (CASE [Private-Accommodation].[maxBrOsoba] WHEN < 3)
WHEN 2 THEN (CASE [Private-Accommodation].[maxBrOsoba] WHEN < 3 AND > 5)
WHEN 3 THEN (CASE [Private-Accommodation].[maxPersons] BETWEEN 4 AND 6)
END

1 个答案:

答案 0 :(得分:2)

如果/ case逻辑超出where子句,通常会更清楚。你可能会考虑:

WHERE [Private-Accommodation].[Otok] = 'Rab' AND 
      ((@iKapacitet = 1 AND [Private-Accommodation].[maxPersons] < 3) OR
       (@iKapacitet = 2 AND [Private-Accommodation].[maxPersons] < 3) AND [Private-Accommodation].[maxPersons] > 5) OR
       (@iKapacitet NOT IN (1, 2) AND [Private-Accommodation].[maxPersons] BETWEEN 4 AND 6)
      )