2017-08-17 81 views
0

當我運行下面的SQL語句的「nvarchar的值‘雜項’轉換爲數據類型爲int時轉換失敗」:我得到一個錯誤,當我使用group by子句

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 

我得到一個錯誤:

Conversion failed when converting the nvarchar value 'MISCELLANEOUS' to data type 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 

我無法弄清楚它有什麼問題。

+1

可能是您的數據raw_value的值爲'MISCELLANEOUS',並且您試圖將其轉換爲int,作爲** cast(raw_value AS INT)**,因此會顯示錯誤。 –

+0

是的,列raw_value類型是sql_variant,它的值是MISCELLANEOUS,但Where子句會將其過濾掉,問題是第二條語句工作的原因 –

+3

問題是,查詢優化器可以重新排序它的計算方式該聲明 - 不能保證在試圖進行「int」轉換之前應用「where」子句過濾器。這就是爲什麼我總是推薦使用變體的設計,而不是使用多個列來存儲可能存儲的各種類型的值(使用適當的檢查約束來確保正確的列基於預期的類型爲null/not null被存儲) –

回答

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

0

爲了避免這個問題,我省篩選出的數據通過將where子句添加到臨時表中,然後執行int轉換。