Showing posts with label dbs. Show all posts
Showing posts with label dbs. Show all posts

Wednesday, March 7, 2012

Execute sql on multiple objects (DBs or tables)

Hi,
Because I'me a newbie on this... and I don't want to make a monstrous-query, please some advice on this:

In pseudo-code:

for objectname in (specified list of objects)
do
some sql code (i.e. create table xyz)
done

With 'objects' I mean a database or table name.

I've searched and found the foreachdb option, but I don't want to execute the sql n ALL db's but only the ones specified.

Any help is appreciated!sticking to your '(list of objects)' syntax, you could do this:

declare @.x int
declare @.dbname varchar(500)
set @.x = 1

create table #databases
(
ID int IDENTITY,
name varchar(500)
)

insert #databases
select name
from master..sysdatabases
where name in(<your list of databases separated by comma>)

while @.x <= (select max(id) from #databases)
begin
select @.dbname = name from #databases where id = @.x
--<capture @.dbname for dynamic sql>
print @.dbname
set @.x = @.x + 1
end

drop table #databases

Good luck.