转载

SQL Server查看login所授予的具体权限

在SQL Server数据库中如何查看一个登录名(login)的具体权限呢,如果使用SSMS的UI界面查看登录名的具体权限的话,用户数据库非常多的话,要梳理完它所有的权限,操作又耗时又麻烦,个人十分崇尚简洁、高效的方法,反感那些需要大量手工操作的UI界面操作方式,哪怕就是脚本,如果不能一次搞定,手工多操作几次(例如,切换数据库),都是不可接受的。最近遇到这个需求,就完善了一下之前的脚本get_login_rights_script.sql,输入登录名参数,将这个登录名所拥有的服务器角色、数据库角色、以及所授予具体对象的相关权限使用脚本查询出来,脚本分享如下:

 

--==================================================================================================================
--        ScriptName            :            get_login_rights_script.sql
--        Author                :            潇湘隐者    
--        CreateDate            :            2015-12-18
--        Description           :            查看某个登录名被授予的数据库对象的权限的脚本(授权脚本和回收权限脚本)
--        Note                  :             
/******************************************************************************************************************
        Parameters              :                                    参数说明
********************************************************************************************************************
            @login_name         :            你要查看权限的登录名(需要输入替换的参数)
********************************************************************************************************************
   Modified Date    Modified User     Version                 Modified Reason
********************************************************************************************************************
    2018-08-03        潇湘隐者         V01.00.00        新建该脚本。
    2019-04-04        潇湘隐者         V01.01.00        Fix掉一个bug,某个表只允许更新某个字段,但是这里显示更新整个表。
    2019-09-25        潇湘隐者         V01.02.00        解决只能查看某个用户数据库,不能查看所有数据库的权限问题。
    2019-09-25        潇湘隐者         V01.03.00        解决数据库名包含中划线[-], 出现下面错误问题
-------------------------------------------------------------------------------------------------------------------
Msg 911, Level 16, State 1, Line 1
Database 'xxxx' does not exist. Make sure that the name is entered correctly.
-------------------------------------------------------------------------------------------------------------------
   2019-09-26         潇湘隐者         V01.04.00        解决系统表和系统视图大小写问题(排序规则区分大小时,会报错)
   2019-09-26         潇湘隐者         V01.04.00        加入数据库角色详细信息
*******************************************************************************************************************/
 
DECLARE @login_name     NVARCHAR(32)= 'test1';
DECLARE @database_name  NVARCHAR(64);
DECLARE @cmdText        NVARCHAR(MAX);
 
 
IF OBJECT_ID('TempDB.dbo.#databases') IS NOT NULL
    DROP TABLE dbo.#databases;
 
CREATE TABLE #databases
(
    database_id     INT,
    database_name   sysname
);
 
IF OBJECT_ID('tempdb.dbo.#user_db_roles') IS NOT NULL 
    DROP TABLE dbo.#user_db_roles;
 
 
CREATE TABLE dbo.#user_db_roles
(
     [DB_NAME]                NVARCHAR(64)
    ,[USER_NAME]              NVARCHAR(64)
    ,[ROLE_NAME]              NVARCHAR(64)
    ,[PRINCIPAL_TYPE_DESC]    NVARCHAR(64)
    ,[CLASS_DESC]             NVARCHAR(64)
    ,[PERMISSION_NAME]        NVARCHAR(64)
    ,[OBJECT_NAME]            NVARCHAR(128)
    ,[PERMISSION_STATE_DESC]  NVARCHAR(128)
);
 
IF OBJECT_ID('tempdb.dbo.#user_object_rights') IS NOT NULL
    DROP TABLE dbo.#user_object_rights;
 
CREATE TABLE dbo.#user_object_rights
(    
    [DATABASE_NAME]        NVARCHAR(128),
    [SCHEMA_NAME]          NVARCHAR(64),
    [OBJECT_NAME]          NVARCHAR(128),
    [USER_NAME]            NVARCHAR(32),
    [PERMISSIONS_TYPE]     CHAR(12),
    [PERMISSION_NAME]      NVARCHAR(128),
    [PERMISSION_STATE]     NVARCHAR(64),
    [CLASS_DESC]           NVARCHAR(64),
    [COLUMN_NAME]          NVARCHAR(32),
    [STATE_DESC]           NVARCHAR(64),
    [GRANT_STMT]           NVARCHAR(MAX),
    [REVOKE_STMT]          NVARCHAR(MAX)
)
 
INSERT  INTO #databases
SELECT  database_id ,
        name
FROM    sys.databases
WHERE name NOT IN ('model') AND state = 0; --state_desc=ONLINE 
 
 
--登录名授予的服务器角色
SELECT  UserName          = u.name ,
        ServerRole        = g.name ,
        Type              = u.type,
        Type_Desc         = u.Type_Desc,
        Create_Date       = u.create_date,
        Modify_Date       = u.modify_date, 
        DenyLogin         = l.denylogin
FROM    sys.server_role_members m
        INNER JOIN sys.server_principals g ON g.principal_id = m.role_principal_id
        INNER JOIN sys.server_principals u ON u.principal_id = m.member_principal_id
        INNER JOIN sys.syslogins l ON u.name = l.name
WHERE l.name=@login_name
ORDER BY u.name,g.name;
 
 
WHILE 1= 1
BEGIN
 
 
    SELECT TOP 1 @database_name= database_name   
    FROM #databases
    ORDER BY database_id;
 
    IF @@ROWCOUNT =0 
        BREAK;
 
 
    SET @cmdText =  N'USE ' + QUOTENAME(@database_name) + N';' +CHAR(10)
 
    --登录名授予的数据库角色
    /********************************************************************************
    SELECT @cmdText += N'INSERT INTO #user_db_roles
                        SELECT  DB_NAME()     AS [DB_NAME]
                               ,M.NAME        AS [USER_NAME]
                               ,R.NAME        AS [ROLE_NAME]
                        FROM    sys.database_role_members RM
                                INNER JOIN sys.database_principals R ON RM.ROLE_PRINCIPAL_ID = R.PRINCIPAL_ID
                                INNER JOIN sys.database_principals M ON RM.MEMBER_PRINCIPAL_ID = M.PRINCIPAL_ID
                        WHERE M.NAME=@p_login_name' + CHAR(10);
    
    EXEC SP_EXECUTESQL @cmdText, N'@p_login_name NVARCHAR(32)',@p_login_name=@login_name;
    ***********************************************************************************/
    SELECT @cmdText += N'INSERT INTO #user_db_roles
                       SELECT  DB_NAME() AS [DB_NAME] ,
                               u.name AS [USER_NAME] ,
                               r.name AS [ROLE_NAME] ,
                               t.[PRINCIPAL_TYPE_DESC] ,
                               t.[CLASS_DESC] ,
                               t.[PERMISSION_NAME] ,
                               t.[OBJECT_NAME] ,
                               t.PERMISSION_STATE_DESC
                       FROM    sys.database_role_members AS m
                               INNER JOIN sys.database_principals AS r ON r.principal_id = m.role_principal_id
                               INNER JOIN sys.database_principals AS u ON u.principal_id = m.member_principal_id
                               LEFT JOIN ( SELECT  USER_NAME(p.grantee_principal_id) AS principal_name ,
                                                   dp.type_desc AS PRINCIPAL_TYPE_DESC ,
                                                   p.class_desc AS CLASS_DESC ,
                                                   p.permission_name AS [PERMISSION_NAME] ,
                                                   OBJECT_NAME(p.major_id) AS [OBJECT_NAME] ,
                                                   p.state_desc AS [PERMISSION_STATE_DESC]
                                           FROM    sys.database_permissions p
                                                   INNER JOIN sys.database_principals dp ON p.grantee_principal_id = dp.principal_id
                                         ) t ON t.principal_name = r.name
                       WHERE   u.name = @p_login_name;' + CHAR(10);
    
    EXEC SP_EXECUTESQL @cmdText, N'@p_login_name NVARCHAR(32)',@p_login_name=@login_name;
 
    SET @cmdText =  N'USE ' +QUOTENAME(@database_name)  + N';' +CHAR(10);
 
    --查看具体对象的授权问题
    SELECT @cmdText +=N'INSERT INTO dbo.#user_object_rights
                        (    [DATABASE_NAME]        ,
                            [SCHEMA_NAME]           ,
                            [OBJECT_NAME]           ,
                            [USER_NAME]             ,
                            [PERMISSIONS_TYPE]      ,
                            [PERMISSION_NAME]       ,
                            [PERMISSION_STATE]      ,
                            [CLASS_DESC]            ,
                            [COLUMN_NAME]           ,
                            [STATE_DESC]            ,
                            [GRANT_STMT]            ,
                            [REVOKE_STMT]        
                        )
                        SELECT DB_NAME()                    AS  [DATABASE_NAME]
                             , sys.schemas.NAME             AS  [SCHEMA_NAME]
                             , ob.NAME                      AS  [OBJECT_NAME]
                             , sys.database_principals.NAME AS  [USER_NAME]
                             , dp.TYPE                      AS  [PERMISSIONS_TYPE]
                             , dp.PERMISSION_NAME           AS  [PERMISSION_NAME]
                             , dp.STATE                     AS  [PERMISSION_STATE]
                             , dp.CLASS_DESC                AS  [CLASS_DESC]
                             , sc.name                      AS  [COLUMN_NAME]
                             , dp.STATE_DESC                AS  [STATE_DESC]
                             , dp.STATE_DESC + '' '' + dp.PERMISSION_NAME + '' ON [''+ sys.schemas.NAME + ''].['' + ob.NAME + ''] TO ['' + sys.database_principals.NAME + ''];'' COLLATE LATIN1_GENERAL_CI_AS 
                                                            AS  [GRANT_STMT] 
                             , ''REVOKE '' + dp.PERMISSION_NAME + '' ON [''+ sys.schemas.NAME + ''].['' + ob.NAME + ''] FROM ['' + sys.database_principals.NAME + ''];'' COLLATE LATIN1_GENERAL_CI_AS 
                                                            AS  [REVOKE_STMT]
                        FROM sys.database_permissions  dp
                        LEFT OUTER JOIN sys.objects  ob ON dp.MAJOR_ID = ob.OBJECT_ID 
                        LEFT OUTER JOIN sys.schemas ON  ob.SCHEMA_ID = sys.schemas.SCHEMA_ID 
                        LEFT OUTER JOIN sys.database_principals ON dp.GRANTEE_PRINCIPAL_ID = sys.database_principals.PRINCIPAL_ID 
                        LEFT OUTER JOIN sys.columns sc ON ob.object_id = sc.object_id AND sc.column_id = dp.minor_id
                        WHERE sys.database_principals.NAME =@p_login_name
                        ORDER BY PERMISSIONS_TYPE;'
 
    --PRINT(@cmdText);
    EXEC SP_EXECUTESQL @cmdText, N'@p_login_name NVARCHAR(32)',@p_login_name=@login_name;
 
    DELETE FROM #databases WHERE database_name=@database_name;
END
 
SELECT * FROM tempdb.dbo.#user_db_roles;
SELECT * FROM tempdb.dbo.#user_object_rights;
 
 
IF OBJECT_ID('TempDB.dbo.#databases') IS NOT NULL
    DROP TABLE dbo.#databases;
IF OBJECT_ID('tempdb.dbo.#user_db_roles') IS NOT NULL 
    DROP TABLE dbo.#user_db_roles;
IF OBJECT_ID('tempdb.dbo.#user_object_rights') IS NOT NULL
    DROP TABLE dbo.#user_object_rights;

 

---------------------------------------------------------------分割线-------------------------------------------------------------------------------

最近在使用过程中,发现这个SQL漏掉了查询登录名所授予的服务器级权限,今天有空,特此补充,修改一下这篇博客的内容。

--==================================================================================================================
--        ScriptName            :            get_login_rights_script.sql
--        Author                :            潇湘隐者    
--        CreateDate            :            2015-12-18
--        Description           :            查看某个登录名被授予的数据库对象的权限的脚本(授权脚本和回收权限脚本)
--        Note                  :            
/*******************************************************************************************************************
        Parameters            :                                    参数说明
********************************************************************************************************************
            @login_name       :            你要查看权限的登录名(需要输入替换的参数)
********************************************************************************************************************
        Notice                :            由于系统视图的缺陷,此脚本无法显示服务器角色public、数据库角色public
********************************************************************************************************************
   Modified Date    Modified User     Version                 Modified Reason
********************************************************************************************************************
    2018-08-03        潇湘隐者         V01.00.00        新建该脚本。
    2019-04-04        潇湘隐者         V01.01.00        Fix掉一个bug,某个表只允许更新某个字段,但是这里显示更新整个表。
    2019-09-25        潇湘隐者         V01.02.00        解决只能查看某个用户数据库,不能查看所有数据库的权限问题。
    2019-09-25        潇湘隐者         V01.03.00        解决数据库名包含中划线[-], 出现下面错误问题
    2019-09-26        潇湘隐者         V01.04.00        解决系统表和系统视图大小写问题(排序规则区分大小时,会报错)
    2019-09-26        潇湘隐者         V01.04.00        加入数据库角色详细信息
    2019-11-22        潇湘隐者         V01.04.00        解决SQL不能查询到授予的服务器级权限的Bug
*******************************************************************************************************************/
--==================================================================================================================
 
DECLARE @login_name     NVARCHAR(32)= 'test';
DECLARE @database_name  NVARCHAR(64);
DECLARE @cmdText        NVARCHAR(MAX);
 
 
IF OBJECT_ID('TempDB.dbo.#databases') IS NOT NULL
    DROP TABLE dbo.#databases;
 
CREATE TABLE #databases
(
    database_id        INT,
    database_name      sysname
);
 
IF OBJECT_ID('tempdb.dbo.#user_db_roles') IS NOT NULL 
    DROP TABLE dbo.#user_db_roles;
 
--CREATE TABLE dbo.#user_db_roles
--(
--     [DB_NAME]      NVARCHAR(64)
--    ,[USER_NAME]    NVARCHAR(64)
--    ,[ROLE_NAME]    NVARCHAR(64)
--);
CREATE TABLE dbo.#user_db_roles
(
     [DB_NAME]                NVARCHAR(64)
    ,[USER_NAME]              NVARCHAR(64)
    ,[ROLE_NAME]              NVARCHAR(64)
    ,[PRINCIPAL_TYPE_DESC]    NVARCHAR(64)
    ,[CLASS_DESC]             NVARCHAR(64)
    ,[PERMISSION_NAME]        NVARCHAR(64)
    ,[OBJECT_NAME]            NVARCHAR(128)
    ,[PERMISSION_STATE_DESC]  NVARCHAR(128)
);
 
IF OBJECT_ID('tempdb.dbo.#user_object_rights') IS NOT NULL
    DROP TABLE dbo.#user_object_rights;
 
CREATE TABLE dbo.#user_object_rights
(    
    [DATABASE_NAME]        NVARCHAR(128),
    [SCHEMA_NAME]          NVARCHAR(64),
    [OBJECT_NAME]          NVARCHAR(128),
    [USER_NAME]            NVARCHAR(32),
    [PERMISSIONS_TYPE]     CHAR(12),
    [PERMISSION_NAME]      NVARCHAR(128),
    [PERMISSION_STATE]     NVARCHAR(64),
    [CLASS_DESC]           NVARCHAR(64),
    [COLUMN_NAME]          NVARCHAR(32),
    [STATE_DESC]           NVARCHAR(64),
    [GRANT_STMT]           NVARCHAR(MAX),
    [REVOKE_STMT]          NVARCHAR(MAX)
)
 
INSERT  INTO #databases
SELECT  database_id ,
        name
FROM    sys.databases
WHERE name NOT IN ('model') AND state = 0; --state_desc=ONLINE 
 
 
--登录名授予的服务器角色
SELECT  UserName        = u.name ,
        ServerRole      = g.name ,
        Type            = u.type,
        Type_Desc       = u.Type_Desc,
        Create_Date     = u.create_date,
        Modify_Date     = u.modify_date, 
        DenyLogin       = l.denylogin
FROM    sys.server_role_members m
        INNER JOIN sys.server_principals g ON g.principal_id = m.role_principal_id
        INNER JOIN sys.server_principals u ON u.principal_id = m.member_principal_id
        INNER JOIN sys.syslogins l ON u.name = l.name
WHERE l.name=@login_name
ORDER BY u.name,g.name;
 
 
--登录名授予的服务器级权限
SELECT  grantor_principal.name  AS [Grantor] ,
        prmssn.state            AS [PermissionState] ,
        prmssn.state_desc       AS [PermissionStateDesc],    
        prmssn.type             AS [PermissionCode] ,
        prmssn.permission_name  AS [PermissionName]
FROM    sys.server_permissions AS prmssn
        INNER JOIN sys.server_principals AS grantor_principal ON grantor_principal.principal_id = prmssn.grantor_principal_id
        INNER JOIN sys.server_principals AS grantee_principal ON grantee_principal.principal_id = prmssn.grantee_principal_id
WHERE   grantee_principal.name = @login_name
ORDER BY [PermissionName] DESC;
 
WHILE 1= 1
BEGIN
 
 
    SELECT TOP 1 @database_name= database_name   
    FROM #databases
    ORDER BY database_id;
 
    IF @@ROWCOUNT =0 
        BREAK;
 
 
    SET @cmdText =  N'USE ' + QUOTENAME(@database_name) + N';' +CHAR(10)
 
    --登录名授予的数据库角色
    /********************************************************************************
    SELECT @cmdText += N'INSERT INTO #user_db_roles
                        SELECT  DB_NAME()   AS [DB_NAME]
                               ,M.NAME        AS [USER_NAME]
                               ,R.NAME        AS [ROLE_NAME]
                        FROM    sys.database_role_members RM
                                INNER JOIN sys.database_principals R ON RM.ROLE_PRINCIPAL_ID = R.PRINCIPAL_ID
                                INNER JOIN sys.database_principals M ON RM.MEMBER_PRINCIPAL_ID = M.PRINCIPAL_ID
                        WHERE M.NAME=@p_login_name' + CHAR(10);
    
    EXEC SP_EXECUTESQL @cmdText, N'@p_login_name NVARCHAR(32)',@p_login_name=@login_name;
    ***********************************************************************************/
    SELECT @cmdText += N'INSERT INTO #user_db_roles
                       SELECT  DB_NAME() AS [DB_NAME] ,
                               u.name AS [USER_NAME] ,
                               r.name AS [ROLE_NAME] ,
                               t.[PRINCIPAL_TYPE_DESC] ,
                               t.[CLASS_DESC] ,
                               t.[PERMISSION_NAME] ,
                               t.[OBJECT_NAME] ,
                               t.PERMISSION_STATE_DESC
                       FROM    sys.database_role_members AS m
                               INNER JOIN sys.database_principals AS r ON r.principal_id = m.role_principal_id
                               INNER JOIN sys.database_principals AS u ON u.principal_id = m.member_principal_id
                               LEFT JOIN ( SELECT  USER_NAME(p.grantee_principal_id) AS principal_name ,
                                                   dp.type_desc AS PRINCIPAL_TYPE_DESC ,
                                                   p.class_desc AS CLASS_DESC ,
                                                   p.permission_name AS [PERMISSION_NAME] ,
                                                   OBJECT_NAME(p.major_id) AS [OBJECT_NAME] ,
                                                   p.state_desc AS [PERMISSION_STATE_DESC]
                                           FROM    sys.database_permissions p
                                                   INNER JOIN sys.database_principals dp ON p.grantee_principal_id = dp.principal_id
                                         ) t ON t.principal_name = r.name
                       WHERE   u.name = @p_login_name;' + CHAR(10);
    
    EXEC SP_EXECUTESQL @cmdText, N'@p_login_name NVARCHAR(32)',@p_login_name=@login_name;
 
    SET @cmdText =  N'USE ' +QUOTENAME(@database_name)  + N';' +CHAR(10);
 
    --查看具体对象的授权问题
    SELECT @cmdText +=N'INSERT INTO dbo.#user_object_rights
                        (    [DATABASE_NAME]        ,
                            [SCHEMA_NAME]        ,
                            [OBJECT_NAME]        ,
                            [USER_NAME]            ,
                            [PERMISSIONS_TYPE]    ,
                            [PERMISSION_NAME]    ,
                            [PERMISSION_STATE]    ,
                            [CLASS_DESC]        ,
                            [COLUMN_NAME]        ,
                            [STATE_DESC]        ,
                            [GRANT_STMT]        ,
                            [REVOKE_STMT]        
                        )
                        SELECT DB_NAME()                    AS  [DATABASE_NAME]
                             , sys.schemas.NAME                AS  [SCHEMA_NAME]
                             , ob.NAME                        AS    [OBJECT_NAME]
                             , sys.database_principals.NAME AS    [USER_NAME]
                             , dp.TYPE                        AS  [PERMISSIONS_TYPE]
                             , dp.PERMISSION_NAME            AS    [PERMISSION_NAME]
                             , dp.STATE                        AS    [PERMISSION_STATE]
                             , dp.CLASS_DESC                AS    [CLASS_DESC]
                             , sc.name                        AS  [COLUMN_NAME]
                             , dp.STATE_DESC                AS    [STATE_DESC]
                             , dp.STATE_DESC + '' '' + dp.PERMISSION_NAME + '' ON [''+ sys.schemas.NAME + ''].['' + ob.NAME + ''] TO ['' + sys.database_principals.NAME + ''];'' COLLATE LATIN1_GENERAL_CI_AS 
                                                            AS  [GRANT_STMT] 
                             , ''REVOKE '' + dp.PERMISSION_NAME + '' ON [''+ sys.schemas.NAME + ''].['' + ob.NAME + ''] FROM ['' + sys.database_principals.NAME + ''];'' COLLATE LATIN1_GENERAL_CI_AS 
                                                            AS  [REVOKE_STMT]
                        FROM sys.database_permissions  dp
                        LEFT OUTER JOIN sys.objects  ob ON dp.MAJOR_ID = ob.OBJECT_ID 
                        LEFT OUTER JOIN sys.schemas ON  ob.SCHEMA_ID = sys.schemas.SCHEMA_ID 
                        LEFT OUTER JOIN sys.database_principals ON dp.GRANTEE_PRINCIPAL_ID = sys.database_principals.PRINCIPAL_ID 
                        LEFT OUTER JOIN sys.columns sc ON ob.object_id = sc.object_id AND sc.column_id = dp.minor_id
                        WHERE sys.database_principals.NAME =@p_login_name
                        ORDER BY PERMISSIONS_TYPE;'
 
    --PRINT(@cmdText);
    EXEC SP_EXECUTESQL @cmdText, N'@p_login_name NVARCHAR(32)',@p_login_name=@login_name;
 
    DELETE FROM #databases WHERE database_name=@database_name;
END
 
SELECT * FROM tempdb.dbo.#user_db_roles ORDER BY DB_NAME;
SELECT * FROM tempdb.dbo.#user_object_rights ORDER BY DATABASE_NAME;
 
 
IF OBJECT_ID('TempDB.dbo.#databases') IS NOT NULL
    DROP TABLE dbo.#databases;
IF OBJECT_ID('tempdb.dbo.#user_db_roles') IS NOT NULL 
    DROP TABLE dbo.#user_db_roles;
IF OBJECT_ID('tempdb.dbo.#user_object_rights') IS NOT NULL
    DROP TABLE dbo.#user_object_rights;
正文到此结束
本文目录