您必须确保没有在任何数字列中附加字符串。
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