我猜程序应该是这样的:
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@H_301_4@但问题是exec(‘use’ @ db)不起作用.我总是得到当前所选数据库的用户列表.我该如何解决这个问题? @H_301_4@P.S.:我希望这段代码能够在2000和2005 sql服务器上运行.
解决方法
您还可以使用未记录但使用良好的sp_MSforeachdb存储过程 – 请参阅
here for details或查看另一个
blog post here:
exec sp_MSforeachdb 'select * from ?.sys.sysusers'@H_301_4@“?”是将添加到命令的数据库名称的占位符,因为它是针对系统中的每个数据库执行的.