开发者

SQL Server 2005 Users & Roles

开发者 https://www.devze.com 2022-12-30 06:48 出处:网络
All, I am trying to script out a database in SQL Server Management Studio 2005. In my database users belong to d开发者_StackOverflow中文版ifferent roles.

All,

I am trying to script out a database in SQL Server Management Studio 2005. In my database users belong to d开发者_StackOverflow中文版ifferent roles. Unfortunately I can't find how to script out the relationship between users and roles.

Thanks,

M


The role membership is stored in sys.database_role_members:

select u.name as UserName,
  r.Name as RoleName
from sys.database_principals u
join sys.database_role_members m on u.principal_id = m.member_principal_id
join sys.database_principals r on m.role_principal_id = p.principal_id;

User may still get additional privileges by their server fixed roles membership, which is stored in sys.server_role_memebers and needs to be joined with sys.server_principals.


Here's some code we use to first check if a user is already mapped to a role, and if not, to do the mapping. You should be able to take the TSQL at the top that uses database_prinicipals and database_role_members and use that to extract out the relationships you have in your databaase.

   SELECT @sql = '  IF EXISTS (SELECT  * FROM ' + @DatabaseName + '.sys.database_principals a
            JOIN ' + @DatabaseName + '.sys.database_role_members b ON a.principal_id = b.role_principal_id
            JOIN    ' + @DatabaseName + '.sys.database_principals c ON b.member_principal_id = c.principal_id
            WHERE   a.Type = ''R'' AND a.Name = ''' + @CurrentDbRole + '''
            AND     c.type IN ( ''U'', ''S'') AND c.name = ''' + @MappedUser + ''')'                
        + ' BEGIN
                PRINT '''';
                PRINT N''The [' + @MappedUser + '] user is already a member of the [' 
                        + @CurrentDbRole + '] role in the [' + @DatabaseName + '] database. Skipping Role Member creation.''; 
                PRINT '''';
            END
            ELSE
            BEGIN
                PRINT '''';
                PRINT N''Adding the [' + @MappedUser + '] database user as member of the [' + @CurrentDbRole 
                        + '] role in the [' + @DatabaseName + '] database... '';
                PRINT '''';

                USE ' + @DatabaseName +'; 
                EXECUTE sp_addrolemember [' + @CurrentDbRole + '], [' + @MappedUser + '];   

                PRINT '''';
                PRINT ''Completed adding the user to the role.'';
                PRINT '''';             
            END; ';
0

精彩评论

暂无评论...
验证码 换一张
取 消