在STUFF中使用','时发生转换错误-SQL

时间:2018-10-20 13:24:19

标签: sql sql-server

我有以下查询:

select STUFF((SELECT ',' + rr1._cv_id 
FROM #reportrows rr1 
WHERE rr1._c_id=rr._c_id 
FOR XML PATH('')),1, 1,null)FROM #reportrows rr

在此查询中,_cv_id是整数类型。运行此查询后,我看到以下错误:

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

有帮助吗?!

3 个答案:

答案 0 :(得分:3)

该ID不是字符串,请进行转换:

SELECT STUFF( (SELECT ',' + CONVERT(VARCHAR(MAX), rr1._cv_id)
. . .

答案 1 :(得分:3)

看起来列cv_id是数字数据类型。因此,在连接逗号之前,您需要先转换为字符串

import csv

def get_maxes():
    with open("data.csv", 'r') as data_file:
        data = csv.DictReader(data_file)
        columns_to_process = data.fieldnames[3:] # don't process first 3 colums
        data = [row for row in data] # read all the data from DictReader and store it in the list

        column_max = {}
        for column in columns_to_process:
            column_max[column] = max(data, key=lambda x: x[column])

        return column_max

if __name__ == '__main__':
    import pprint
    pprint.pprint(get_maxes())

答案 2 :(得分:3)

您需要将rr1._cv_id转换为字符串

select STUFF((SELECT ',' + CAST(rr1._cv_id AS VARCHAR(20))
FROM #reportrows rr1 
WHERE rr1._c_id=rr._c_id 
FOR XML PATH('')),1, 1,null)FROM #reportrows rr