2013-11-22 61 views
0

我有其中目標表和where子句條件被指定爲參數的簡單存儲過程。該「算術溢出錯誤轉換nvarchar的數據類型的數字。」錯誤導致我有點挫折。如何解決「將nvarchar轉換爲數據類型數值的算術溢出錯誤。」錯誤?

@TableName varchar(50), -- 'A_RECORD_ETH0' test value 

@Time_ms decimal(18,4), -- '40388629085.6481' test value 

@Records int out,  -- should result with '1' if test values are used 

這工作:

SELECT COUNT(*) as Count FROM A_RECORD_ETH0 WHERE Time_ms = 40388629085.6481 

這工作:

SET @sql = N'SET @Records = (SELECT COUNT(*) FROM A_RECORD_ETH0 WHERE Time_ms = 40388629085.6481)' 

EXEC sp_executesql @sql, N'@Records int output', @Records output 

這工作:

SET @sql = N'SET @Records = (SELECT COUNT(*) FROM '+ @TableName + ' WHERE Time_ms = 40388629085.6481)' 

EXEC sp_executesql @sql, N'@Records int output', @Records output 

這將導致算術溢出錯誤:

SET @sql = N'SET @Records = (SELECT COUNT(*) FROM '+ @TableName + ' WHERE Time_ms = ' + @Time_ms + ')' 

EXEC sp_executesql @sql, N'@Records int output', @Records output 

這將導致算術溢出錯誤即使使用投:

SET @sql = N'SET @Records = (SELECT COUNT(*) FROM '+ @TableName + ' WHERE Time_ms = Cast (' + @Time_ms + ' as decimal(18,4)))' 

EXEC sp_executesql @sql, N'@Records int output', @Records output 

回答

1

直接傳遞@Time_ms可避免decimal-> string-> decimal轉換。它也更高效;當@Time_ms發生變化時,服務器仍然可以重用執行計劃而不是生成新計劃。

SET @sql = N'SET @Records = (SELECT COUNT(*) FROM '+ @TableName + ' WHERE Time_ms = @Time_ms' 

EXEC sp_executesql @sql, N'@Time_ms decimal(18,4), @Records int output', @[email protected]_ms, @Records output 
0

我得到了下面的根據您的工作代碼:

DECLARE @sqlSelect nvarchar(500); 
DECLARE @ParmSelect nvarchar(500); 
SET @sqlSelect = N'SET @RecordsOut = (SELECT COUNT(*) FROM ' + @TableName + ' WHERE Time_ms = @Time_msIn)' 
SET @ParmSelect = N'@Time_msIn decimal(18,4), @RecordsOut int OUTPUT'; 
EXEC sp_executesql @sqlSelect, @ParmSelect, @Time_msIn = @Time_ms, @RecordsOut = @Records OUTPUT; 
相關問題