I am trying to execute statements gained from a cursor, and I keep getting an "Invalid object name" error. To start with, the cursor pulls information from a table that has a database name in one column, and a SQL statement in another. It is defined as such:
DECLARE commands CURSOR FOR
SELECT
REPLACE(DBNAME, DBNAME, 'USE ' + DBNAME),
REPLACE(REPLACE(REPLACE(DESCRIPTION, 'OLDLINKEDSERVER', 'NEWLINKEDSERVER'), 'CREATE VIEW', 'ALTER VIEW'), 'CREATE VIEW', 'ALTER VIEW') AS CMD
FROM
#TMP2
Then, I define two commands:
DECLARE @cmd1 NVARCHAR(MAX)
DECLARE @cmd2 NVARCHAR(MAX)
So cmd1 is really just "USE DBName" where DBName is the name of the database, and cmd2 is a SQL statement to be run on that database.
For some reason, whenever I then iterate through the cursor:
OPEN Commands
FETCH NEXT FROM Commands INTO @cmd1, @cmd2
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC sp_executesql @cmd1
EXEC sp_executesql @cmd2
FETCH NEXT FROM Commands INTO @cmd1, @cmd2
END
CLOSE commands
DEALLOCATE commands
I get an error that says:
Msg 208, Level 16, State 6, Procedure NameOfView, Line 34
Invalid object name 'dbo.NameOfView'.
I've tried adding a "GO" command to cmd1, but it didn't work (I guess GO is only good for client tools). I tried using "exec(@cmd1)" instead of exec sp_executesql(@cm1)". If I tried to make it one command instead of two, it then says "ALTER VIEW must be the first statement in a query batch."
What can I do to get my cursor to work correctly?
EDIT: The following code is the working solution I found, thanks to IsItGreyOrGray (not sure if I'm supposed to edit it into my original post, or create a new one):
code for cursor
declare commands cursor for
SELECT REPLACE(DBNAME,DBNAME, 'USE ' + DBNAME),
REPLACE(REPLACE(REPLACE(DESCRIPTION,'OLDLINKEDSERVER', 'NEWLINKEDSERVER'),'CREATE VIEW', 'ALTER VIEW'), '''', '''''') AS CMD
FROM #TMP2
declarations
declare @cmd1 varchar(max)
declare @cmd2 varchar(max)
iterate through cursor
open commands
fetch next from commands into @cmd1, @cmd2
while @@FETCH_STATUS=0
begin
declare @cmd3 VARCHAR(MAX) = CONCAT(@cmd1, '; declare @cmd1 varchar(max) = ''', @cmd2, ''' exec(@cmd1)')
exec(@cmd3)
fetch next from commands into @cmd1, @cmd2
end
close commands
deallocate commands