2014-01-11 43 views
0

對本論壇的所有成員發出你好,我嘗試使用以下存儲過程將主表中的數據插入臨時表以用於進一步分析目的:將數據類型nvarchar轉換爲數值時遇到錯誤,將數據插入到臨時表中

ALTER PROCEDURE [dbo].[terr_punctuality_comp] AS 

Begin 

CREATE TABLE #previousdata (Rly nvarchar(255), preDirect numeric(18,0), preIndirect numeric(18,0), preIncidences numeric(18,0), preTotal numeric(18,0)) 

INSERT INTO #previousdata SELECT SUM(case when Dir_Ind = 'Dir' then 1 else 0 end) AS 'preDirect', SUM(case when Dir_Ind = 'Ind' then 1 else 0 end) + 
SUM(case when rep1 IS NOT NULL then 1 else 0 end) 
+ SUM(case when rep2 IS NOT NULL then 1 else 0 end) 
+ SUM(case when rep3 IS NOT NULL then 1 else 0 end) 
+ SUM(case when rep4 IS NOT NULL then 1 else 0 end) 
+ SUM(case when rep5 IS NOT NULL then 1 else 0 end)AS 'preIndirect', 
SUM(case when Dir_Ind IS NOT NULL then 1 else 0 end) AS 'preIncidences', 
SUM(case when Dir_Ind = 'Dir' then 1 else 0 end) + SUM(case when Dir_Ind = 'Ind' then 1 else 0 end) + 
SUM(case when rep1 IS NOT NULL then 1 else 0 end) 
+ SUM(case when rep2 IS NOT NULL then 1 else 0 end) 
+ SUM(case when rep3 IS NOT NULL then 1 else 0 end) 
+ SUM(case when rep4 IS NOT NULL then 1 else 0 end) 
+ SUM(case when rep5 IS NOT NULL then 1 else 0 end)AS 'preTotal', 
Rly FROM PunctualityMain 

WHERE Rly IN  ('CR', 'ER', 'ECR', 'ECoR', 'NR', 'NCR', 'NER', 'NFR', 'NWR', 'SR', 'SCR', 'SER', 'SECR', 'SWR', 'WR', 'WCR') 

GROUP BY Rly 

end 

在執行我越來越

錯誤轉換數據類型爲nvarchar到數字。

我的主要表結構

ID int 
Date datetime  
Train int 
Dir_Ind nvarchar(255) 
Detn int 
Rly   nvarchar(255) 
DiV   nvarchar(255) 
rep1 int 
det1 int 
rep2 int 
det2 int 
rep3 int 
det3 int 
rep4 int 
det4 int 
rep5 int 
det5 int 

先生,如何解決這個問題呢?

回答

1

我想你不能依賴別名來設置哪個選定的字段到哪個表字段。相反,您應該在插入時指定字段順序... select like:

INSERT INTO #previousdata(PreDirect,preIndirect,preIncidences,preTotal,Rly)SELECT ...;

否則,數據庫會嘗試將第五個選定字段(Rly,它是nvarchar)放入表的第五個已定義字段(數字爲preTotal)中。

+0

非常感謝。我真是個傻瓜。 – Sunil

相關問題