0

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

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
4

2 回答 2

0

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

于 2013-10-21T07:01:36.763 回答
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
于 2015-06-01T07:23:37.647 回答