CASE表达式

时间:2018-04-03 16:11:41

标签: sql-server-2012 case date-formatting

我正在尝试在下面的SQL

中输出日期格式
CASE
WHEN E.A_EXTTRNDTETME IS NOT NULL then LEFT(E.A_EXTTRNDTETME, 4)
    +SUBSTRING(E.A_EXTTRNDTETME, 5, 2)+SUBSTRING(E.A_EXTTRNDTETME, 7, 2)
    +'-'+SUBSTRING(E.A_EXTTRNDTETME, 9, 2)+':'+SUBSTRING(E.A_EXTTRNDTETME, 11, 2)
    +':'+SUBSTRING(E.A_EXTTRNDTETME, 13,2)+'.'+SUBSTRING(E.A_EXTTRNDTETME, 15,3)
WHEN E.A_EXTTRNDTETME IS NULL then 
(
  SELECT TOP 1 A_EXTTRNDTETME FROM T_ATH_EXE 
  WHERE A_PAREXEID = E.A_EXEID ORDER BY A_ADDDTETME
)
ELSE ' text'
END as [TransactTime], 

第二个WHEN语句返回20180322141422883,但我希望它采用以下格式,如第一个分支的值:

20180322-14:14:22.883

但是不知道如何在SELECT语句中做到这一点,请帮忙。

2 个答案:

答案 0 :(得分:0)

您可以将整个查询放入子查询中,因此您只需要应用一次格式。您也可以使用COALESCE,这只是写CASE WHEN IS NOT NULL THEN this ELSE that END的一种较短方式。最后,还有内置样式选项,用于格式化日期时间值,避免所有混乱的字符串操作(您可以看到all the options here)。

SELECT *, TransactTime = COALESCE
    (
      CONVERT(char(8), dt, 112) + '-' + CONVERT(char(12), dt, 108),
     ' text'
    )
FROM -- your larger query here
(
  SELECT 
    dt = COALESCE
    (
      E.A_EXTTDNDTETME, 
      (
        SELECT TOP (1) A_EXTTRNDTETME 
          FROM T_ATH_EXE 
          WHERE A_PAREXEID = E.A_EXEID 
          ORDER BY A_ADDDTETME
      )
    ), -- other columns... 
  FROM -- table...
) AS sub;

答案 1 :(得分:-1)

我通过以下方式使用它: -

CASE     当E.A_EXTTRNDTETME为NULL时(SELECT top 1 LEFT(A_EXTTRNDTETME,4)+ SUBSTRING(A_EXTTRNDTETME,5,2)+ SUBSTRING(A_EXTTRNDTETME,7,2)+' - '+ SUBSTRING(A_EXTTRNDTETME,9,2)+' :'+ SUBSTRING(A_EXTTRNDTETME,11,2)+':'+ SUBSTRING(A_EXTTRNDTETME,13,2)+'。'+ SUBSTRING(A_EXTTRNDTETME,15,3)FROM T_ATH_EXE WHERE A_PAREXEID = E.A_EXEID ORDER BY E.A_ADDDTETME )     当E.A_EXTTRNDTETME不为空时,则LEFT(E.A_EXTTRNDTETME,4)+ SUBSTRING(E.A_EXTTRNDTETME,5,2)+ SUBSTRING(E.A_EXTTRNDTETME,7,2)+' - '+ SUBSTRING(E.A_EXTTRNDTETME,9 ,2)+':'+ SUBSTRING(E.A_EXTTRNDTETME,11,2)+':'+ SUBSTRING(E.A_EXTTRNDTETME,13,2)+'。'+ SUBSTRING(E.A_EXTTRNDTETME,15,3)     ELSE'文字' 结束为[TransactTime],