使用Case when将nvarchar转换为Int

时间:2019-07-01 15:22:05

标签: sql-server sql-server-2008-r2

当前,我正在尝试将“ 20190208-10h9m / 1/1”转换为数据类型int。该字符串在String_Value列下标识。另外,我将重点介绍使用Case语法。

我尝试过:

CASE WHEN PTXMEDE.PAT_ID = 'ID_TABLET' TEHN PTXMEDE.STRING_VALUE ELSE 0 END), CAST(PTXMEDE.STRING_VALUE As nvarchar) As ID_TABLET

出现转换错误。

完整语法如下:

Select
    PTXMEDE.ME,
    (CASE WHEN PTXMEDE.PAT_ID = 'ID_TABLET' THEN PTXMEDE.STRING_VALUE ELSE 0 END),CAST(PTXMEDE.STRING_VALUE As nvarchar) As ID_TABLET,
    SUM(CASE WHEN PTXMEDE.PAT_ID = 'Q1_MD' THEN PTXMEDE.NUM_VALUE ELSE 0 END) As Q1_MD,
    SUM(CASE WHEN PTXMEDE.PAT_ID = 'Q1_FPROB' THEN PTXMEDE.NUM_VALUE ELSE 0 END) As Q1_FPROB,
    SUM(CASE WHEN PTXMEDE.PAT_ID = 'Q1_RESULT' THEN PTXMEDE.NUM_VALUE ELSE 0 END) As Q1_RESULT,
    SUM(CASE WHEN PTXMEDE.PAT_ID = 'WEIGHT' THEN PTXMEDE.NUM_VALUE ELSE 0 END) As WEIGHT,
    SUM(CASE WHEN PTXMEDE.PAT_ID = 'HARDNESS' THEN PTXMEDE.NUM_VALUE ELSE 0 END) As HARDNESS,
    MAX(CASE WHEN PTXMEDE.PAT_ID = 'WEIGHT.T2+' THEN PTXMEDE.NUM_VALUE ELSE 0 END) As WEIGHTT2ULIMIT,
    MAX(CASE WHEN PTXMEDE.PAT_ID = 'WEIGHT.T2-' THEN PTXMEDE.NUM_VALUE ELSE 0 END) As WEIGHTT2LLIMIT,
    MAX(CASE WHEN PTXMEDE.PAT_ID = 'HARDNESS.T2-' THEN PTXMEDE.NUM_VALUE ELSE 0 END) As HARDNESST2LLIMIT,
    MAX(CASE WHEN PTXMEDE.PAT_ID = 'CQA1Quality' THEN PTXMEDE.NUM_VALUE ELSE 0 END) As CQA1Quality,
    MAX(CASE WHEN PTXMEDE.PAT_ID = 'CQA2Quality' THEN PTXMEDE.NUM_VALUE ELSE 0 END) As CQA2Quality,
    MAX(CASE WHEN PTXMEDE.PAT_ID = 'CQA3Quality' THEN PTXMEDE.NUM_VALUE ELSE 0 END) As CQA2Quality,
    PTXMEDE.DATE_LOCAL,
    PTXMEDE.SEQUENCE
FROM
   PTXMEDE
   JOIN PTXMIIF ON 
   PTXMIIF.ME = PTXMEDE.ME

WHERE
   PTXMEDE.ME IN (
       SELECT ME FROM PTXME
       WHERE CX_STRING_4 = '20190210-6h31m'
       AND MT = 'CDC_CU'
   )
   GROUP By PTXMEDE.ME, PTXMEDE.DATE_LOCAL,PTXMEDE.NUM_VALUE,PTXMEDE.SEQUENCE,PTXMEDE.STRING_VALUE, PTXMEDE.PAT_ID

我的预期结果是能够在STRING_VALUE列下列出该值

1 个答案:

答案 0 :(得分:1)

CASE表达式的所有分支在SQL中必须具有相同的类型。一个“例外”就是它们具有相同的类型,但是数据库会进行一些隐式转换为正确的事情(例如在MySQL中)。这是CASE表达式的更正版本:

CASE WHEN PTXMEDE.PAT_ID = 'ID_TABLET' THEN PTXMEDE.STRING_VALUE ELSE '0' END

这将使CASE表达式输出所有文本。如果PTXMEDE.STRING_VALUE可以转换为整数,那么理论上您也可以使用以下方法:

CASE WHEN PTXMEDE.PAT_ID = 'ID_TABLET' THEN CAST(PTXMEDE.STRING_VALUE AS INT) ELSE 0 END

这将使CASE表达式返回一个整数值。