我无法理解为什么我的查询没有做它应该做的事情。它应该在每个数据库中运行命令以获取权限,但它似乎为每个数据库提供相同的权限,就好像它每次都在同一个数据库中运行,只是替换数据库的名称。谢谢你的帮助。
SET NOCOUNT ON
DECLARE @dbs TABLE (dbname VARCHAR(50))
DECLARE @CurrentDB VARCHAR(50)
DECLARE @Permissions TABLE (DBName sysname, UserName sysname,
LoginType sysname, AssociatedRole varchar(max),create_date datetime,
modify_date datetime)
INSERT INTO @dbs (dbname)
SELECT name FROM master.sys.databases WHERE state_desc != 'OFFLINE'
WHILE EXISTS (SELECT dbname FROM @dbs)
BEGIN
SET @CurrentDB = (SELECT TOP 1 dbname FROM @dbs ORDER BY dbname)
INSERT INTO @Permissions
SELECT @CurrentDB AS DBName,
case prin.name when 'dbo' then prin.name + ' ('+ (select SUSER_SNAME(owner_sid) from master.sys.databases where name = @CurrentDB) + ')' else prin.name end AS UserName,
prin.type_desc AS LoginType,
isnull(USER_NAME(mem.role_principal_id),'') AS AssociatedRole ,create_date,modify_date
FROM sys.database_principals prin
LEFT OUTER JOIN sys.database_role_members mem ON prin.principal_id=mem.member_principal_id
WHERE prin.sid IS NOT NULL and prin.sid NOT IN (0x00) and
prin.is_fixed_role <> 1 AND prin.name NOT LIKE '##%'
DELETE FROM @dbs WHERE dbname = @CurrentDB
END
SELECT * FROM @Permissions