如何在t-sql中获取所有数据库名称及其用户名和角色的列表?

时间:2016-05-09 11:41:53

标签: sql sql-server

我试图用他们的用户名和角色获取所有数据库名称的列表。像这样: image

这是我的代码,但我只能得到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 个答案:

答案 0 :(得分:2)

您可以这样使用:

$category = Mage::getModel('catalog/category');

                try{
                    $category->setName($cat['category_name'])
                         ->setUrlKey(str_replace(" " , "-" , strtolower($cat['category_name'])))
                         ->setIsActive(1)
                         ->setDisplayMode('PRODUCTS')
                         ->setStoreId(0)
                         ->setPath('1/2')
                         ->save();

                }catch(Exception $e)
                {
                    die($e->getMessage());
                }

                    if($category->getId() == 0): die("Category Didnt Save!"); endif;

答案 1 :(得分: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