2013-10-21 91 views
0

當我運行這段代碼它給我的錯誤,我沒有什麼不對的錯誤轉換數據類型爲varchar爲bigint SQL錯誤

DECLARE @COUNTER BIGINT 
DECLARE @SQL varchar (800) 

DECLARE @SQL2 nvarchar(max) = N'SELECT @Counter = MIN(CAST('[email protected]+' AS BIGINT)) FROM '[email protected]+' WHERE dbo.IsInteger('[email protected]+') = 1 and '[email protected]+' >=''' [email protected]+''' and '[email protected]+' <= '''[email protected]+'''' 

PRINT @SQL2 

-- EXEC @SQL 
EXEC sp_executesql @SQL2, N'@Counter BIGINT OUTPUT', @Counter = @Counter OUTPUT 

PRINT @Counter 
+1

你的問題提到不清楚。你是否聲明@fieldand是什麼類型的? –

+1

'@ cfield'是否包含一些無法轉換爲'bigint'的值?另外,當使用'PRINT @ SQL2'打印時,查詢的效果如何? – jpw

+0

@cfield is varchar ... and ddatefrm and ddateto is varchar –

回答

0

它看起來像@cfield被聲明爲varchar。它包含的數值可以轉換爲bigint,但如果contais字符值不能轉換爲bigint。

0

你必須確保你沒有附加任何帶有字符串的數字列。

DECLARE @COUNTER BIGINT; 
DECLARE @SQL VARCHAR(800); 
DECLARE @SQL2 NVARCHAR(MAX) = N'SELECT @Counter = MIN(CAST(' 
        + CAST(@cfield as varchar(100))+ ' AS BIGINT)) FROM ' 
        + CAST(@ctable AS varchar(100)) 
        + ' WHERE dbo.IsInteger(' + CAST(@cfield as varchar(100)) 
        + ') = 1 and ' + cast(@cdatefield as varchar(100)) 
        + ' >=''' + cast(@ddatefrm as varchar(100))+ ''' and ' 
        + cast(@cdatefield as varchar(100)) 
        + ' <= ''' + cast(@ddateto as varchar(100)) + ''''; 
PRINT @SQL2; 

-- EXEC @SQL 
EXEC sp_executesql 
    @SQL2, 
    N'@Counter BIGINT OUTPUT', 
    @Counter = @Counter OUTPUT; 
PRINT @Counter; 

對於上面的SQL Server 2012 &,您可以試試這個。

DECLARE @COUNTER BIGINT 
DECLARE @SQL varchar (800) 

DECLARE @SQL2 nvarchar(max) = concat(N'SELECT @Counter = MIN(CAST(' 
          ,@cfield,' AS BIGINT)) FROM ',@ctable,' WHERE dbo.IsInteger(' 
          ,@cfield+') = 1 and ',@cdatefield,' >=''' 
          ,@ddatefrm,''' and ' 
          ,@cdatefield,' <= ''',@ddateto,'''') 

PRINT @SQL2 

-- EXEC @SQL 
EXEC sp_executesql @SQL2, N'@Counter BIGINT OUTPUT', @Counter = @Counter OUTPUT 

PRINT @Counter 
相關問題