I have T-SQL code that is used to run utilities against a particular list of databases that are stored in a table. I have a cursor that gets the list of DBs from the sysdatabases table based on entries in a table in a specific database. The list of databases will vary from server to server, so I need to have it use variables rather than code the db names into the script.
declare @.DatabaseId char(8)
declare DatabaseLoop cursor for
select name from master..sysdatabases where name in
(select <column name> from <db name..table> )
open DatabaseLoop
fetch next from DatabaseLoop into @.DatabaseId
while (@.@.fetch_status <> -1)
begin
...
So far, the context has not mattered, for example - backup @.DatabaseID works fine within the cursor since the context doesn't need to change. The problem is that I want to run particular scripts that require the context to be changed to the database. But, of course, USE @.DatabaseID does not work inside the cursor.
So, is there another way to be able to run my script against multiple variables other than using a cursor?
I am not necessarily looking for you to write my code, but if someone could point me in the right direction, I would appreciate it.
I would suggest that you use dynamic SQL for this and you can use a use in there.
declare @.query varchar(8000) -- I am assuming 2000 since you
--used sysdatabases
set @.query = 'use ' + @.database + ' select * from sysobjects'
exec (@.query)
I know this works in 2005, and am pretty sure it worked in 2000
Edit: Sorry, sent the message from my phone and it did a terrible job with the formatting
No comments:
Post a Comment