Hello,
I have been using dynamic sql in an inner cursor and I get an error about the fetched variable of the outer cursor. How can I fix it?
DECLARE A1 CURSOR GLOBAL FOR SELECT Iid, Server, Dbname FROM @OuterTable; OPEN A1; FETCH NEXT FROM A1 INTO @aId, @aServer, @aDbname; WHILE @@fetch_status <> -1 BEGIN SET @SQLCursor = 'DECLARE D1 CURSOR GLOBAL FOR SELECT Id, StatusId, Server, DbName FROM [' + @aServer + '].['+@aDbname+'].dbo.Rooms;'; EXEC sp_executesql @SQLCursor; OPEN D1; FETCH NEXT FROM D1 INTO @dId, @dStatusId, @dServer, @dDbname; WHILE @@fetch_status <> -1 BEGIN SET @SQL='SELECT @aId, @dId, @dStatusId, d.DateCreated, d.DocumentSize, dah.ActivityId, dah.DocDeleted FROM [' + @dServer + '].['+@dDbname+'].dbo.Documents d INNER JOIN DocumentActivityHistory dah ON d.Id = dah.DocumentId;'; INSERT INTO @DocActivity EXEC sp_executesql @SQL; --, '@aId nvarchar(50) output',@aId output; FETCH NEXT FROM D1 INTO @dId, @dStatusId, @dServer, @dDbname; END CLOSE D1; DEALLOCATE D1; FETCH NEXT FROM A1 INTO @aId, @aServer, @aDbname; END CLOSE A1; DEALLOCATE A1;
And the error is;
Msg 137, Level 15, State 2, Line 1Must declare the scalar variable "@aId".
Thanks,