I'm trying to insert into a @table
parameter using OPENROWSET
with a @param
in a loop. I've adapted code from: This Answer, which demonstrates using Dynamic SQL to insert the parameter.
Code:
DECLARE @BuildTimes TABLE (
BuildTableName VARCHAR(max) NULL
,BuildDate DATE NULL
)
DECLARE @days INT = 0;
DECLARE @startDate DATE = GETDATE();
DECLARE @buildDate DATE = GETDATE();
DECLARE @sql nvarchar(max);
WHILE (@days <=30)
BEGIN
SET @buildDate = DATEADD(day, -1*@days, @startDate);
SET @sql='INSERT INTO @BuildTimes
SELECT *
FROM OPENROWSET(
''SQLNCLI'',
''SERVER=localhost;Trusted_Connection=yes;'',
''EXEC [LOG].[BuildTimes] @buildDate = ''''' + CAST(@buildDate AS VARCHAR) +''''''')'
PRINT @sql
EXEC(@sql)
SET @days = @days + 1
END
SELECT * FROM @BuildTimes
Error:
Msg 1087, Level 15, State 2, Line 9
Must declare the table variable "@BuildTimes"
I've tried running the OPENROWSET as non-dynamic SQL without the param and it all works properly. What am I doing wrong?