将数据类型varchar转换为bigint SQL ERROR时出错

时间:2013-10-21 06:46:01

标签: sql sql-server

当我运行此代码时,它给了我一个错误,我不知道这个

有什么问题
DECLARE @COUNTER BIGINT
DECLARE @SQL  varchar (800)

DECLARE @SQL2 nvarchar(max) = 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

2 个答案:

答案 0 :(得分:0)

看起来@cfield被声明为varchar。它包含数值,可以转换为bigint。但是如果包含的字符值不能转换为bigint。

答案 1 :(得分: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&amp;以上你可以试试这个。

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