我收到错误"转换nvarchar值时转换失败' MISCELLANEOUS'数据类型int"当我使用group by子句时

时间:2017-08-17 06:07:22

标签: sql sql-server

当我运行以下SQL语句时:

SELECT 
    timecollected, SUM(waitingtaskscounttotal) waitingtaskscounttotal 
FROM 
    (SELECT 
         timecollected, CAST(raw_value AS INT) AS waitingtaskscounttotal
     FROM 
         spotlight_perfdata sp
     JOIN 
         spotlight_stat_names sn ON sp.statistic_name_id = sn.statistic_name_id
                                 AND sn.statistic_class_id = CONVERT(NVARCHAR, @statistic_class_id)
     WHERE 
         sp.statistic_class_id = CONVERT(NVARCHAR, @statistic_class_id)
         AND (sp.timecollected >= convert(NVARCHAR, @firstdate, 126)
              AND sp.timecollected <= convert(NVARCHAR, @lastdate, 126))
         AND sp.monitored_object_id = CONVERT(NVARCHAR, @monitored_object_id)
         AND sn.statistic_name = 'waitingtaskscounttotal') TableA
GROUP BY 
    timecollected
ORDER BY 
    timecollected DESC

我收到错误:

  

转换nvarchar值时转换失败&#39; MISCELLANEOUS&#39;数据类型int。

但是在我从SQL语句中删除了列timecollected之后,它起作用了:

SELECT 
    SUM(waitingtaskscounttotal) waitingtaskscounttotal 
FROM 
    (SELECT 
         timecollected, CAST(raw_value AS INT) AS waitingtaskscounttotal
     FROM 
         spotlight_perfdata sp
     JOIN 
         spotlight_stat_names sn ON sp.statistic_name_id = sn.statistic_name_id
                                 AND sn.statistic_class_id = CONVERT(NVARCHAR, @statistic_class_id)
     WHERE 
         sp.statistic_class_id = CONVERT(NVARCHAR, @statistic_class_id)
         AND (sp.timecollected >= convert(NVARCHAR, @firstdate, 126)
              AND sp.timecollected <= convert(NVARCHAR, @lastdate, 126))
         AND sp.monitored_object_id = CONVERT(NVARCHAR, @monitored_object_id)
         AND sn.statistic_name = 'waitingtaskscounttotal') TableA

我无法弄清楚它有什么问题。

2 个答案:

答案 0 :(得分:0)

改变这个:

CAST(raw_value AS INT)

到此:

CASE 
WHEN raw_value like '%[0-9]%' and not raw_value like '%[^0-9]%' 
OR raw_value like '-%[0-9]%' and not raw_value like '-%[^0-9]%' 
THEN CAST(raw_value AS int)
ELSE NULL
END

这将使一切不是int NULL

答案 1 :(得分:0)

为避免此问题,我将where子句筛选出的数据保存到临时表中,然后进行int转换。