along with a very good explanation
1: SET NOCOUNT ON
2: DECLARE @OldUser sysname, @NewUser sysnameSET @OldUser = 'HRUser'SET @NewUser = 'PersonnelAdmin'
3: SELECT 'USE' + SPACE(1) + QUOTENAME(DB_NAME()) AS '--Database Context'SELECT '--Cloning permissions from' + SPACE(1) + QUOTENAME(@OldUser) + SPACE(1) + 'to' + SPACE(1) + QUOTENAME(@NewUser) AS '--Comment'SELECT 'EXEC sp_addrolemember @rolename =' + SPACE(1) + QUOTENAME(USER_NAME(rm.role_principal_id), '''') + ', @membername =' + SPACE(1) + QUOTENAME(@NewUser, '''') AS '--Role Memberships'
4: FROM sys.database_role_members AS rm
5: WHERE USER_NAME(rm.member_principal_id) = @OldUser
6: ORDER BY rm.role_principal_id ASC
7: SELECT CASE
8: WHEN perm.state <> 'W'
9: THEN perm.state_desc
10: ELSE 'GRANT'
11: END + SPACE(1) + perm.permission_name + SPACE(1) + 'ON ' + QUOTENAME(USER_NAME(obj.schema_id)) + '.' + QUOTENAME(obj.name) +
12: CASE WHEN cl.column_id IS NULL THEN SPACE(0)
13: ELSE '(' + QUOTENAME(cl.name) + ')'
14: END + SPACE(1) + 'TO' + SPACE(1) + QUOTENAME(@NewUser)
15: COLLATE database_default + CASE WHEN perm.state <> 'W'
16: THEN SPACE(0)
17: ELSE SPACE(1) + 'WITH GRANT OPTION' END AS '--Object Level Permissions'
18: FROM sys.database_permissions AS perm
19: INNER JOIN sys.objects AS obj ON perm.major_id = obj.[object_id]
20: INNER JOIN sys.database_principals AS usr
21: ON perm.grantee_principal_id = usr.principal_id
22: LEFT JOIN sys.columns AS cl
23: ON cl.column_id = perm.minor_id
24: AND cl.[object_id] = perm.major_id
25: WHERE usr.name = @OldUser
26: ORDER BY perm.permission_name ASC, perm.state_desc ASC
27: SELECT CASE WHEN perm.state <> 'W' THEN perm.state_desc
28: ELSE 'GRANT' END + SPACE(1) + perm.permission_name + SPACE(1) + SPACE(1) + 'TO' + SPACE(1) + QUOTENAME(@NewUser)
29: COLLATE database_default +
30: CASE WHEN perm.state <> 'W' THEN SPACE(0) ELSE SPACE(1) + 'WITH GRANT OPTION' END AS '--Database Level Permissions'
31: FROM sys.database_permissions AS perm
32: INNER JOIN sys.database_principals AS usr
33: ON perm.grantee_principal_id = usr.principal_id
34: WHERE usr.name = @OldUser
35: AND perm.major_id = 0
36: ORDER BY perm.permission_name ASC, perm.state_desc ASC
No comments:
Post a Comment