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
@qsince you cannot parameterize table names even in dynamic SQL; the whole statement must be generated dynamically, since@tblNamemust be interpolated into the text. If you set@tblNamebefore producing@qyou have the same effect as you'd have in a loop.'SELECT ...' + @tblName + ' WHERE ...'is correct, but then@tblNamemust already have a value there, and should not be passed as a parameter. In your example,DECLARE @tblName AS SYSNAME = 'myTestTable'.INSERT ... EXECworks with table variables, so the remainder of the code is fine. TheINSERTof course should not happen inside the dynamically generated statement, as then you can't reference the outer scope's variables.