2016-05-09 66 views
1

我想用他們的用戶名和角色來獲取所有數據庫名稱的列表。就像這樣: image如何在t-sql中使用其用戶名和角色獲取所有數據庫名稱的列表?

這裏是我的代碼,但我只能得到DBNAME:

SELECT 
    LEFT(ltrim(rtrim(@@ServerName)), Charindex('\', ltrim(rtrim(@@ServerName))) -1) servername 
    ,CONVERT(nvarchar,dec.local_net_address) AS IPAdress 
    ,suser_sname(owner_sid) as 'LocalAdmin' 
    , db.name AS dbname 
FROM sys.dm_exec_connections AS dec 
CROSS JOIN sys.databases db 
WHERE dec.session_id = @@SPID AND suser_sname(owner_sid) <> 'sa' 

回答

2

你可以使用這樣的:

DECLARE @DB_USers TABLE (
    DBName SYSNAME 
    ,UserName SYSNAME 
    ,LoginType SYSNAME 
    ,AssociatedRole VARCHAR(max) 
    ,create_date DATETIME 
    ,modify_date DATETIME 
    ) 

INSERT @DB_USers 
EXEC sp_MSforeachdb ' 
use [?] 
SELECT ''?'' AS DB_Name, 
case prin.name when ''dbo'' then prin.name + '' (''+ (select SUSER_SNAME(owner_sid) from master.sys.databases where name =''?'') + '')'' 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 ''##%''' 

SELECT dbname 
    ,username 
    ,logintype 
    ,create_date 
    ,modify_date 
    ,STUFF((
      SELECT ',' + CONVERT(VARCHAR(500), associatedrole) 
      FROM @DB_USers user2 
      WHERE user1.DBName = user2.DBName 
       AND user1.UserName = user2.UserName 
      FOR XML PATH('') 
      ), 1, 1, '') AS Permissions_user 
FROM @DB_USers user1 
GROUP BY dbname 
    ,username 
    ,logintype 
    ,create_date 
    ,modify_date 
ORDER BY DBName 
    ,username 
+0

謝謝,它對我很有用。另外我想添加列「database_id」,我該怎麼做? –

0

這裏有一個查詢,讓您的結果,作爲同您鏈接的圖像:

CREATE TABLE [dbo].[#Temp] (
[SERVER NAME] VARCHAR(250) null, 
[IP ADDRESS] VARCHAR(32) null, 
[DATABASE NAME] NVARCHAR(128) NULL, 
[USERNAME] CHAR(25) NULL, 
[DATABASE ROLE] CHAR(25) NULL 
) 

EXEC sp_msForEachDB 
'INSERT INTO #Temp 
    SELECT 
     CONVERT(VARCHAR(250), SERVERPROPERTY(''ServerName''))   AS ServerName 
     ,CONVERT(VARCHAR(32), CONNECTIONPROPERTY(''local_net_address'')) AS local_net_address 
     ,''?''      AS ''dbName'' 
     ,CONVERT(CHAR(25),dbp.name) AS dbUser 
     ,CONVERT(CHAR(25),dbp2.name) AS dbRole 
    FROM sys.server_principals AS sp 
    JOIN [?].sys.database_principals AS dbp ON sp.sid=dbp.sid 
    JOIN [?].sys.database_role_members AS dbrm ON dbp.principal_Id=dbrm.member_principal_Id 
    JOIN [?].sys.database_principals AS dbp2 ON dbrm.role_principal_id=dbp2.principal_id 
    LEFT JOIN sys.server_role_members AS srm ON sp.principal_id=srm.member_principal_id 
    LEFT JOIN sys.server_principals AS sp2 ON srm.role_principal_id=sp2.principal_id' 

SELECT * FROM #Temp 

結果:

enter image description here

相關問題