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 below, 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
Also I would pass @Bound arguments to the sp_executesql procedure as well:
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