Skip to content
Advertisement

Need to declare a cursor with a variable in the declaration

I had a problem with a maintenance procedure and need to create a second one where I declare a cursor with a list of database ID and pass them into another cursor to get a list of tables for each database.

Current problem is that in the inner cursor even though it runs use [database_name], when i declare it and specify my query it selects the tables from the master database. it doesn’t change the database context before going into the inner cursor.

GO

Advertisement

Answer

The issue with your inner cursor, is scope. You can to do 2 things here. You have to move your inner cursor to right after the USE [' + @db like:

Or you can get rid of the inner cursor altogether and use sys.sp_MSforeachtable:

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement