sql-server – 如何获取所有实例数据库的用户列表

我猜程序应该是这样的:
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

但问题是exec(‘use’ @ db)不起作用.我总是得到当前所选数据库用户列表.我该如何解决这个问题?

P.S.:我希望这段代码能够在2000和2005 sql服务器上运行.

解决方法

您还可以使用未记录但使用良好的sp_MSforeachdb存储过程 – 请参阅 here for details或查看另一个 blog post here
exec sp_MSforeachdb 'select * from ?.sys.sysusers'

“?”是将添加到命令的数据库名称的占位符,因为它是针对系统中的每个数据库执行的.

相关文章

SELECT a.*,b.dp_name,c.pa_name,fm_name=(CASE WHEN a.fm_n...
if not exists(select name from syscolumns where name=&am...
select a.*,pano=a.pa_no,b.pa_name,f.dp_name,e.fw_state_n...
要在 SQL Server 2019 中设置定时自动重启,可以使用 Window...
您收到的错误消息表明数据库 &#39;EastRiver&#39; 的...
首先我需要查询出需要使用SQL Server Profiler跟踪的数据库标...