I guess the procedure should be something like this:
declare @db varchar(100)
declare @user varchar(100)
declare c cursor for select name from sys.sysdatabases
open c
fetch next from c into @db
while @@fetch_status = 0
begin
print @db
exec ('use ' + @db)
declare u cursor for select name from sys.sysusers
where issqlrole <> 1 and hasdbaccess <> 0 and isntname <> 1
open u
fetch next from u into @user
while @@fetch_status = 0
begin
print @user
fetch next from u into @user
end
print '--------------------------------------------------'
close u
deallocate u
fetch next from c into @db
end
close c
deallocate c
But the problem is that exec ('use ' + @db) doesn't work. And i always get user list of currently chosen database. How should i fix that?
P.S.: I want this code to work on both 2000 and 2005 sql servers.
You could also use the undocumented but well used
sp_MSforeachdb
stored proc - see here for details or see another blog post here:The "?" is the placeholder for the database name that will be added to the command, as it gets executed against each database in your system.
Here is a nice query from http://www.sqlservercentral.com/scripts/Administration/63841/ If you do not have an account, it is a free signup and a very nice resource.
Puts everything in a temp table, then you can do whatever you want with it.
Here's how to create a list of all users of all databases in a SQL Server instance. I think that's what you're looking for.
If you want a list of all users for all databases for all instances you should be able to modify the script to do that. Just expand on the techniques used in the script.
https://tidbytez.com/2018/02/05/how-to-create-a-list-of-all-users-of-all-databases-in-a-sql-server-instance/