2012-05-15 62 views
2

如何在SQL查询中使用'case'语句的嵌套形式。我正在尝试执行以下查询。嵌套“CASE when”语句

SELECT AccessTabF1.Month, AccessTabF1.Year, AccessTabF1.[Entity Number], 
case when [Exp Year]= 2010 + 1 
    then 'Expires in 1 to 5 Years' 
    else 
      case when [Exp Year]>2010 + 5 
       then 'Expires After 5 Years' 
       else 'No Expiration Year Listed' 
end 
from AccessTabF1 
+6

您需要用'end'关闭每个案例。 –

+3

也只是要清楚'CASE'是一个表达式,返回一个单一的值,而不是一个语句。把它称为一个声明可能是导致它被用来控制流动的误解,就像它在其他语言中一样。 –

回答

12

在你的情况下,你不需要嵌套多个CASE表达式。

SELECT AccessTabF1.Month, AccessTabF1.Year, AccessTabF1.[Entity Number], 
case when [Exp Year] = 2010 + 1 -- why not = 2011 ? 
    then 'Expires in 1 to 5 Years' -- this does not match the logic on line above 
    when [Exp Year] > 2010 + 5 -- why not > 2015 ? 
    then 'Expires After 5 Years' 
    else 'No Expiration Year Listed' 
end 
from AccessTabF1