带有列前缀的SQL子查询

时间:2014-08-06 18:06:25

标签: sql tsql stored-procedures sql-server-2012

我有一个大的存储过程,其中有一个子查询,如下所示。

SELECT COUNT(userID) AS totalLikes FROM apsLikes WHERE likeID = 'empowerment_'+A.[submissionID]
FOR    XML PATH ('likes'), TYPE, ELEMENTS

likeID列中,我的值为prefix_id

当我尝试运行查询时出现此错误:

Conversion failed when converting the varchar value 'empowerment_' to data type int.

likeID的数据类型是varchar(60),所以不确定它是什么意思?

3 个答案:

答案 0 :(得分:0)

只需做一个明确的cast()

SELECT COUNT(userID) AS totalLikes
FROM apsLikes
WHERE likeID = 'empowerment_' + cast(A.[submissionID] as varchar(255))
FOR    XML PATH ('likes'), TYPE, ELEMENTS;

问题是+可能意味着添加或字符串连接。因为第二个参数是整数,所以它假定+是加法,并且'empowerment_'不能转换为整数。因此,错误。

答案 1 :(得分:0)

SubmissionID可能是数据typeint。试试这个。

SELECT COUNT(userID) AS totalLikes 
FROM apsLikes WHERE likeID = 'empowerment_'+ CAST(A.[submissionID] AS NVARCHAR(255))
FOR    XML PATH ('likes'), TYPE, ELEMENTS

答案 2 :(得分:0)

问题是SQL Server将加号解释为加法运算符而不是连接运算符。试试这个:

SELECT COUNT(userID) AS totalLikes 
FROM apsLikes WHERE likeID = 'empowerment_'+ CAST(A.[submissionID] AS VARCHAR(50))
FOR XML PATH ('likes'), TYPE, ELEMENTS