[英]Convert INT to String when using STUFF Function in SQL Server 2016
I'm trying to convert an INT
but it is having an issue with the conversion. 我正在尝试转换INT
但转换存在问题。
Conversion failed when converting the
nvarchar
value '245428,246425' to data typeint
. 将nvarchar
值'245428,246425'转换为数据类型int
时,转换失败。
The query I am using: 我正在使用的查询:
SELECT STUFF
(
(
SELECT DISTINCT ',' + CONVERT(VARCHAR(20), NumField)
FROM Table A
WHERE ID = 218554
FOR XML PATH('')
) ,1,1,''
)
I use this as a subquery in a larger table like so: 我将其用作较大表中的子查询,如下所示:
SELECT
Field1,
Field2,
CASE WHEN criteria = '1'
THEN (SELECT STUFF(
(
SELECT DISTINCT ',' + CONVERT(VARCHAR(20), NumField)
FROM Table A
WHERE ID = 218554
FOR XML PATH('')
) ,1,1,''
))
END
FROM
Table B
The STUFF
query runs fine when it's executed on it's own but when I run it in the full query it comes up with the conversion error. STUFF
执行时, STUFF
查询运行良好,但是当我在完整查询中运行它时,它会带来转换错误。
I don't think you are not showing the full query -- or at least the full case
expression. 我认为您没有显示完整的查询-或至少没有完整的case
表达。 A case
expression returns a single value with a single type. case
表达式返回具有单个类型的单个值。
When there are type conflicts, then SQL Server has to determine the single overall type, according to its rules. 如果存在类型冲突,则SQL Server必须根据其规则确定单个总体类型。 If one then
returns an integer and another returns a string, then the case
expression is an integer ( not a string). 如果一个then
返回一个整数,另一个返回一个字符串,则case
表达式是一个整数( 不是字符串)。 So, the string is converted to an integer. 因此,字符串将转换为整数。
You can see this problem with much simpler logic: 您可以通过更简单的逻辑看到此问题:
select (case when 1=1 then 'a' else 0 end)
Even though the else
is never execution, the type of the expression is determined at compile time -- and 'a'
cannot be converted to an integer. 即使else
永远不会执行,表达式的类型还是在编译时确定的-并且'a'
不能转换为整数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.