I'm attempting to select a row count from a list of tables which exists as a column of data inside a temporary table. I tried to do this with a cursor to build the query string as shown be开发者_JAVA百科low, but this did not work because when I attempt to execute the statement it cannot reference the variable @Rows which was declared earlier in the statement.
This is the first method I attempted which failed with the error "Must declare the scalar variable @Rows"
SELECT @SQL = N'SELECT @Rows = @Rows + '
SELECT @SQL = @SQL + N'(SELECT COUNT(*) FROM [dbo].[' + @Table + '] '
SELECT @SQL = @SQL + N'WHERE tran_date < ' + CONVERT(VARCHAR(20), @Bound, 101) + ')'
Then I attempted the below, which also did not work and failed with a syntax error
SELECT @SQL = N'(SELECT COUNT(*) FROM [dbo].[' + @Table + '] '
SELECT @SQL = @SQL + N'WHERE date < ' + CONVERT(VARCHAR(20), @Bound, 101) + ')'
SELECT @Rows = @Rows + EXEC(@SQL)
Use *sp_executesql* to pass arguments to dynamic sql
DECLARE @Rows BIGINT
SELECT @SQL = N'SELECT @Rows = @Rows + '
SELECT @SQL = @SQL + N'(SELECT COUNT(*) FROM [dbo].[' + @Table + '] '
SELECT @SQL = @SQL + N'WHERE tran_date < ' + CONVERT(VARCHAR(20), @Bound, 101) + ')'
EXEC sp_executesql N'@Rows BIGINT', @SQL, @Rows = @Rows OUTPUT
Also I would pass @Bound arguments to the sp_executesql procedure as well:
DECLARE @Rows BIGINT
SELECT @SQL = N'SELECT @Rows = @Rows + '
SELECT @SQL = @SQL + N'(SELECT COUNT(*) FROM [dbo].[' + @Table + '] '
SELECT @SQL = @SQL + N'WHERE tran_date < @Bound)'
EXEC sp_executesql N'@Bound DATETIME, @Rows BIGINT OUTPUT', @SQL, @Bound = @Bound, @Rows = @Rows OUTPUT
Thus you get the benefit of caching the query plan
DavidW:
I was getting some syntax errors, but the below worked succesfully. Thanks for pointing me in the right direction
SELECT @SQL = N'(SELECT @RowsOut = COUNT(*) FROM [dbo].[' + @Table + '] '
SELECT @SQL = @SQL + N'WHERE tran_date < CONVERT(DATETIME,@BoundIn))'
PRINT 'SQL:' + @SQL + ' Bound: ' + CONVERT(VARCHAR(12),@Bound,101)
EXEC sp_executesql @SQL, N'@BoundIN SQL_VARIANT, @RowsOut INT OUTPUT', @BoundIn = @Bound, @RowsOut = @Rows OUTPUT
精彩评论