伙计们,我已经阅读了这个问题的修复程序,但我有一个我无法解决的变体。
首先,以下语法抛出错误
Case
when #TFs.lTFID = 1161165 then REPLACE(CONVERT(VARCHAR(11), cast([dCreatedUTC] as datetime), 106), ' ', '-')
when #TFs.lTFID = 1161166 then 'Administrator'
when #TFs.lTFID = 1161167 then ''
when #TFs.lTFID = 1161168 then AssetID
when #TFs.lTFID = 1161169 then ''
when #TFs.lTFID = 1161170 then ''
when #TFs.lTFID = 1161172 then ''
when #TFs.lTFID = 1161173 then ''
else CAST(#TFs.lTFID as varchar(20))
End 'Value'
如果我注释掉除了其中一条“when”行以外的所有行,它就会起作用。
Case
when #TFs.lTFID = 1161165 then REPLACE(CONVERT(VARCHAR(11), cast([dCreatedUTC] as datetime), 106), ' ', '-')
/* when #TFs.lTFID = 1161166 then 'Administrator'
when #TFs.lTFID = 1161167 then ''
when #TFs.lTFID = 1161168 then AssetID
when #TFs.lTFID = 1161169 then ''
when #TFs.lTFID = 1161170 then ''
when #TFs.lTFID = 1161172 then ''
when #TFs.lTFID = 1161173 then ''*/
else CAST(#TFs.lTFID as varchar(20))
End 'Value'
有关如何格式化此查询以使所有“案例”都有效的任何想法?
答案 0 :(得分:3)
根据错误消息,CASE
表达式的结果将转换为INT
。除了WHEN
之外,VARCHAR
的返回值也称为AssetID
,因此我认为这必须是INT
值。
发生错误是因为使用CASE
表达式时,所有返回值必须是相同的数据类型。如果它们具有不同的数据类型,则所有值都将转换为具有更高data type precedence的类型。
由于INT
的优先级高于VARCHAR
,因此结果会转换为导致错误的INT
。要解决此问题,您还必须将AssetID
转换为VARCHAR(n)
Case
when #TFs.lTFID = 1161165 then REPLACE(CONVERT(VARCHAR(11), cast([dCreatedUTC] as datetime), 106), ' ', '-')
when #TFs.lTFID = 1161166 then 'Administrator'
when #TFs.lTFID = 1161167 then ''
when #TFs.lTFID = 1161168 then CAST(AssetID AS VARCHAR(20))
when #TFs.lTFID = 1161169 then ''
when #TFs.lTFID = 1161170 then ''
when #TFs.lTFID = 1161172 then ''
when #TFs.lTFID = 1161173 then ''
else CAST(#TFs.lTFID as varchar(20))
End 'Value'
答案 1 :(得分:1)
尝试将AssetID转换为case语句中的varchar。
Case
when #TFs.lTFID = 1161165 then REPLACE(CONVERT(VARCHAR(11), cast([dCreatedUTC] as datetime), 106), ' ', '-')
when #TFs.lTFID = 1161166 then 'Administrator'
when #TFs.lTFID = 1161167 then ''
when #TFs.lTFID = 1161168 then CAST(AssetID AS VARCHAR(20))
when #TFs.lTFID = 1161169 then ''
when #TFs.lTFID = 1161170 then ''
when #TFs.lTFID = 1161172 then ''
when #TFs.lTFID = 1161173 then ''
else CAST(#TFs.lTFID as varchar(20))
End 'Value'
答案 2 :(得分:0)
试试这个
Case #TFs.lTFID
When 1161165 then REPLACE(CONVERT(VARCHAR(11), cast([dCreatedUTC] as datetime), 106), ' ', '-')
When 1161166 then 'Administrator'
.
.
.
Else CAST(#TFs.lTFID as varchar(20)) END
答案 3 :(得分:-2)
将CAST
放在CASE
之外,如下所示:
CAST(
Case
when #TFs.lTFID = 1161165 then REPLACE(CONVERT(VARCHAR(11), cast([dCreatedUTC] as datetime), 106), ' ', '-')
when #TFs.lTFID = 1161166 then 'Administrator'
when #TFs.lTFID = 1161167 then ''
when #TFs.lTFID = 1161168 then AssetID
when #TFs.lTFID = 1161169 then ''
when #TFs.lTFID = 1161170 then ''
when #TFs.lTFID = 1161172 then ''
when #TFs.lTFID = 1161173 then ''
else #TFs.lTFID
End
as varchar(20)) 'Value'