我有其中目標表和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