Advertisement
kavallo

Duplicar Permisos de SQL a Otros Usuarios

Aug 7th, 2015
306
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.31 KB | None | 0 0
  1. --- To copy permissions of one user/role to another user/role.
  2.  
  3. SET NOCOUNT ON
  4. DECLARE @OldUser sysname, @NewUser sysname
  5.  
  6. SET @OldUser = 'usuario desde' --the user or role from which to copy the permissions from
  7. SET @NewUser = 'usuario hasta' --the user or role to which to copy the permissions to
  8.  
  9.  
  10. SELECT 'USE' + SPACE(1) + QUOTENAME(DB_NAME()) AS '--Database Context'
  11.  
  12.  
  13. SELECT '--Cloning permissions from' + SPACE(1) + QUOTENAME(@OldUser) + SPACE(1) + 'to' + SPACE(1) + QUOTENAME(@NewUser) AS '--Comment'
  14.  
  15.  
  16. SELECT 'EXEC sp_addrolemember @rolename ='
  17. + SPACE(1) + QUOTENAME(USER_NAME(rm.role_principal_id), '''') + ', @membername =' + SPACE(1) + QUOTENAME(@NewUser, '''') AS '--Role Memberships'
  18. FROM sys.database_role_members AS rm
  19. WHERE USER_NAME(rm.member_principal_id) = @OldUser
  20. ORDER BY rm.role_principal_id ASC
  21.  
  22.  
  23. SELECT CASE WHEN perm.state <> 'W' THEN perm.state_desc ELSE 'GRANT' END
  24. + SPACE(1) + perm.permission_name + SPACE(1) + 'ON ' + QUOTENAME(USER_NAME(obj.schema_id)) + '.' + QUOTENAME(obj.name)
  25. + CASE WHEN cl.column_id IS NULL THEN SPACE(0) ELSE '(' + QUOTENAME(cl.name) + ')' END
  26. + SPACE(1) + 'TO' + SPACE(1) + QUOTENAME(@NewUser) COLLATE database_default
  27. + CASE WHEN perm.state <> 'W' THEN SPACE(0) ELSE SPACE(1) + 'WITH GRANT OPTION' END AS '--Object Level Permissions'
  28. FROM sys.database_permissions AS perm
  29. INNER JOIN
  30. sys.objects AS obj
  31. ON perm.major_id = obj.[object_id]
  32. INNER JOIN
  33. sys.database_principals AS usr
  34. ON perm.grantee_principal_id = usr.principal_id
  35. LEFT JOIN
  36. sys.columns AS cl
  37. ON cl.column_id = perm.minor_id AND cl.[object_id] = perm.major_id
  38. WHERE usr.name = @OldUser
  39. ORDER BY perm.permission_name ASC, perm.state_desc ASC
  40.  
  41.  
  42. SELECT CASE WHEN perm.state <> 'W' THEN perm.state_desc ELSE 'GRANT' END
  43. + SPACE(1) + perm.permission_name + SPACE(1)
  44. + SPACE(1) + 'TO' + SPACE(1) + QUOTENAME(@NewUser) COLLATE database_default
  45. + CASE WHEN perm.state <> 'W' THEN SPACE(0) ELSE SPACE(1) + 'WITH GRANT OPTION' END AS '--Database Level Permissions'
  46. FROM sys.database_permissions AS perm
  47. INNER JOIN
  48. sys.database_principals AS usr
  49. ON perm.grantee_principal_id = usr.principal_id
  50. WHERE usr.name = @OldUser
  51. AND perm.major_id = 0
  52. ORDER BY perm.permission_name ASC, perm.state_desc ASC
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement