加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

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

发布时间:2020-12-12 08:52:51 所属栏目:MsSql教程 来源:网络整理
导读:我猜程序应该是这样的: declare @db varchar(100)declare @user varchar(100)declare c cursor for select name from sys.sysdatabases open cfetch next from c into @dbwhile @@fetch_status = 0begin print @db exec ('use ' + @db) declare u cursor for
我猜程序应该是这样的:
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'

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读