SQL中的Case语句给出错误

时间:2014-11-03 16:04:24

标签: sql sql-server

我正在尝试编写一个查询,该输出将输出为MONTH,YEAR。

当我写:

 select CAST( tbl.MONTH as varchar(2) ) + ', ' + CAST ( tbl.YEAR as varchar(4) ) as [DATE] 
 from TABLE as tbl

我得到输出为

    1,2014
    4,2014 (depending upon the input)

但是,现在,我想用JAN替换1,用DECRIL 12替换DEC

所以,我试着写一个案例陈述:

SELECT 
    case when tbl.MONTH ='1' 
    then ('JAN' + ', ' + CAST ( tbl.YEAR as varchar(4) )) as [DATE1]  
from TABLE as tbl

这会产生语法错误。 谁能告诉我,我应该做什么?

4 个答案:

答案 0 :(得分:6)

case需要end

SELECT (case when tbl.MONTH = '1' then 'JAN' + ', ' + CAST(tbl.YEAR as varchar(4) ))
        end) as [DATE1]
from TABLE tbl;

如果值存储为数字,则不要在常量值周围放置单引号。

答案 1 :(得分:1)

您缺少关闭end声明所需的case

case
when tbl.MONTH ='1'
then ('JAN' + ', ' + CAST ( tbl.YEAR as varchar(4) ))
end
as [DATE1] 
from TABLE as tbl

答案 2 :(得分:1)

简单的方法是使用 Datename 内置函数。无需CASE statement对所有月份进行硬编码

SELECT Datename(mm, tbl.[MONTH]) + ', '
       + CONVERT(VARCHAR(10), tbl.YEAR) AS [DATE]
FROM   TABLE AS tbl 

或者如果您使用的是sql server 2012

SELECT Choose(tbl.[MONTH], 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')
       + ', ' + CONVERT(VARCHAR(10), tbl.YEAR) AS [DATE]
FROM   TABLE AS tbl 

答案 3 :(得分:0)

与普拉迪普的答案类似,但是使用了来自https://stackoverflow.com/a/188390/405180的方便的小DATENAME修正,并修剪为前3个字符:

SELECT UPPER(LEFT(Datename(MONTH , DateAdd( MONTH , tbl.[MONTH] , -1 )), 3)) + ', ' + CONVERT(VARCHAR(10), tbl.[YEAR]) AS [DATE]
FROM   TABLE AS tbl

TBH,我认为从性能的角度来看,您最好使用CASE tbl.[MONTH] WHEN 1 THEN 'JAN' WHEN ...方法。