July 4, 2006 at 5:43 am
Hi, my t-sql skills are fairly limited so I hope you can help with this. I'm trying to run the following, but as one proc so it runs the same query in each database on the server and gives me back one result set covering all DB's
select db_name() as [DB Name],
name as [User],
CASE hasdbaccess
WHEN '0' THEN 'NO'
WHEN '1' THEN 'YES'
END as [Has DB Access]
from sysusers
where name in ('guest','public')
I've tried a cursor, selecting each dbname from sysdatabases and then executing with sp_executesql but of course it execs from the DB its currently in.
Any pointers would be much appreciated.
Many Thanks
July 4, 2006 at 6:52 am
declare @db table (id int identity(0, 1), name sysname)
insert @db
(
name
)
select name
from master..sysdatabases
where dbid > 4 -- remove system databases
order by case when name = db_name() then 0 else 1 end
create table #output (name sysname, sysname, access bit)
declare @id int,
@name sysname,
@sql varchar(1000)
select @id = max(id)
from @db
while @id >= 0
begin
select @name = name,
@sql = 'USE ' + quotename(@name)
from @db
where id = @id
exec (@sql)
select @sql = 'insert #output (name, , access) select ''' + @name + ''', su.name, su.hasdbaccess from ' + quotename(@name) + '..sysusers su where su.name in (''guest'', ''public'')'
exec (@sql)
select @id = @id - 1
end
select * from #output
drop table #output
N 56°04'39.16"
E 12°55'05.25"
July 4, 2006 at 7:59 am
Or...
create table #output (name sysname, sysname, access bit)
exec sp_MSforeachdb @command1 =
'insert #output select ''?'', name, hasdbaccess from ?.dbo.sysusers where name in (''guest'', ''public'')'
select * from #output where db_id(name) > 4
drop table #output
This uses the undocumented stored procedure sp_MSforeachdb, which you can read about here, should you wish:
http://www.databasejournal.com/features/mssql/article.php/3441031
Clearly this method is neat, but you should take into account the warning notes at the bottom of the above link.
Ryan Randall
Solutions are easy. Understanding the problem, now, that's the hard part.
July 5, 2006 at 3:16 am
Thats great, thanks very much to you both !
July 5, 2006 at 11:04 am
BTW- You can always tools like SQL Farm Combine to run the simple query against as many databases as you wish, across multiple servers as well.
Editor's Note: : Dr. Omri Bahat works for SQLFarms, a software vendor of SQL Server tools.
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply