2013-09-27 103 views
0

我目前在SQL Server 2005中使用下面的代碼來獲取孤立用戶SID的數據,這很好,但我真的需要獲得關於每個孤兒userSID的角色成員信息,這是可能的,如果是這樣,我怎麼能寫這個查詢?SQL Server - 從孤兒UserSID獲取數據庫角色成員

DECLARE cur CURSOR FAST_FORWARD FOR 
SELECT name FROM sys.databases 
WHERE database_id > 4 

OPEN cur 

DECLARE @SQL NVARCHAR(MAX), @DBName SYSNAME 
DECLARE @Results TABLE (DBName SYSNAME, UserName SYSNAME, UserSID VARBINARY(MAX)) 

FETCH NEXT FROM cur into @DBName 

WHILE @@FETCH_STATUS = 0 
BEGIN 
    SET @SQL = 'USE ' + @DBName + ';SELECT ''' + @DBName + ''' AS DBName, 
      UserName = name, UserSID = sid from sysusers 
      WHERE issqluser = 1 AND 
       (sid IS NOT NULL AND sid <> 0x0) AND 
       (LEN(sid) <= 16) AND SUSER_SNAME(sid) IS NULL'  

    INSERT INTO @Results 
    EXEC(@SQL) 

    FETCH NEXT FROM cur into @DBName 
END 

CLOSE cur 
DEALLOCATE cur 

SELECT * FROM @Results 

謝謝!

感謝您的回覆,我已經創建了下面的查詢,基於迄今給出的信息,這看起來像它給我所需要的?

select u.uid, u.name, u.sid, rm.role_principal_id as 'Role ID', dp1.name as 'Role' 
from sys.sysusers u 
left join sys.syslogins l on UPPER(u.sid) = UPPER(l.sid) 
inner join sys.database_role_members rm on rm.member_principal_id = u.uid 
left join sys.database_principals dp on dp.principal_id = rm.member_principal_id 
left join sys.database_principals dp1 on dp1.principal_id = rm.role_principal_id 
where u.uid > 4 and u.issqlrole = 0 
and issqluser = 1 
and l.name is null 
order by u.name 

回答

0

它選擇用戶成員資格。

select case when SUSER_SNAME(dp.sid) is null then dp.name else SUSER_SNAME(dp.sid) end 'dbUser', 
dp2.name 'dbRole', dp.type_desc uDesc 
from sys.database_principals dp left join sys.database_role_members dr 
on dr.member_principal_id = dp.principal_id 
left join sys.database_principals dp2 on dr.role_principal_id = dp2.principal_id 
where dp.type_desc <> 'DATABASE_ROLE' 
and case when SUSER_SNAME(dp.sid) is null then dp.name else SUSER_SNAME(dp.sid) end 
not in ('sys', 'INFORMATION_SCHEMA', 'guest') 
order by 1 

我注意到你的遊標只能選擇孤立的SQL登錄。你需要孤立的Windows登錄嗎?如果是,則檢查以下查詢。

select u.name, * 
from sys.sysusers u left join sys.syslogins l on UPPER(u.sid) = UPPER(l.sid) 
where u.uid > 4 and u.issqlrole = 0 
and l.name is null 
order by u.name 
+0

我想我快到了,我已經構建了相關的查詢,希望能夠將相關ID和角色拉過來。 – Matt

相關問題