I am trying to loop through a temp table variable that contains a list of table names. I want to simply count the rows in each table where a DateTracked column is greater than 30 days. I am having trouble dynamically changing the FROM @tblName variable to store the record count and then insert it into my tracking table. Eventually I will use a cursor to loop through each, but I just want to get this logic down first for a single table. Here is my test code:
DECLARE @tblName as NVARCHAR(MAX)
DECLARE @q as NVARCHAR(MAX)
SET @q = 'Select Count(DateTracked) FROM Audit.' + @tblName + ' WHERE DateTracked > DATEADD(dd, -30, CAST(GETDATE() as date))'
--DECLARE @tblNameTable TABLE
--(
-- tableName NVARCHAR(MAX)
--)
--INSERT INTO @tblNameTable VALUES (N'myTestTable')
DECLARE @ExpectedRecordsToMove AS TABLE (col1 int)
INSERT INTO @ExpectedRecordsToMove EXECUTE sp_executesql @q, N'@tblName nvarchar(500)', @tblName = 'myTestTable'
SELECT * FROM @ExpectedRecordsToMove
@q
since you cannot parameterize table names even in dynamic SQL; the whole statement must be generated dynamically, since@tblName
must be interpolated into the text. If you set@tblName
before producing@q
you have the same effect as you'd have in a loop.'SELECT ...' + @tblName + ' WHERE ...'
is correct, but then@tblName
must already have a value there, and should not be passed as a parameter. In your example,DECLARE @tblName AS SYSNAME = 'myTestTable'
.INSERT ... EXEC
works with table variables, so the remainder of the code is fine. TheINSERT
of course should not happen inside the dynamically generated statement, as then you can't reference the outer scope's variables.