-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsp_CopyDatabasePrinciplePermissions.sql
75 lines (61 loc) · 2.24 KB
/
sp_CopyDatabasePrinciplePermissions.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
USE [master]
GO
IF (OBJECT_ID('[dbo].[sp_CopyDatabasePrinciplePermissions]') IS NULL)
EXEC ('CREATE PROCEDURE [dbo].[sp_CopyDatabasePrinciplePermissions] AS RETURN')
GO
ALTER PROCEDURE [dbo].[sp_CopyDatabasePrinciplePermissions]
@CopyFromPrinciple NVARCHAR(128),
@CopyToPrinciple NVARCHAR(128)
AS
BEGIN
PRINT 'Copying permissions in [' + DB_NAME() + ']'
DECLARE @PermissionCommand NVARCHAR(500)
DECLARE csrPermission CURSOR FAST_FORWARD FOR
SELECT
[state_desc] + ' ' + [permission_name] + ' '
+
CASE
WHEN [class_desc] = 'OBJECT_OR_COLUMN' THEN
'ON [' + OBJECT_SCHEMA_NAME([major_id]) + '].[' + OBJECT_NAME([major_id]) + '] '
ELSE ''
END
+ 'TO [' + @CopyToPrinciple + '];' COLLATE DATABASE_DEFAULT AS [PermissionCommand]
FROM sys.database_permissions permission
INNER JOIN sys.database_principals principle
ON principle.principal_id = permission.grantee_principal_id
WHERE [class_desc] IN ('OBJECT_OR_COLUMN', 'DATABASE')
AND principle.[name] = @CopyFromPrinciple
OPEN csrPermission
FETCH NEXT FROM csrPermission INTO @PermissionCommand
WHILE (@@FETCH_STATUS = 0)
BEGIN
PRINT ' ' + @PermissionCommand
EXEC (@PermissionCommand)
FETCH NEXT FROM csrPermission INTO @PermissionCommand
END
CLOSE csrPermission
DEALLOCATE csrPermission
-- Role memberships
DECLARE csrRoleMembership CURSOR FAST_FORWARD FOR
SELECT
'EXEC sp_addrolemember N''' + rolePrinciple.[name] + ''', N''' + @CopyToPrinciple + ''''
FROM sys.database_role_members drm
INNER JOIN sys.database_principals rolePrinciple
ON rolePrinciple.[principal_id] = drm.[role_principal_id]
INNER JOIN sys.database_principals memberPrinciple
ON memberPrinciple.[principal_id] = drm.[member_principal_id]
WHERE memberPrinciple.[name] = @CopyFromPrinciple
OPEN csrRoleMembership
FETCH NEXT FROM csrRoleMembership INTO @PermissionCommand
WHILE (@@FETCH_STATUS = 0)
BEGIN
PRINT ' ' + @PermissionCommand
EXEC (@PermissionCommand)
FETCH NEXT FROM csrRoleMembership INTO @PermissionCommand
END
CLOSE csrRoleMembership
DEALLOCATE csrRoleMembership
END
GO
--EXEC sys.sp_MS_marksystemobject 'sp_CopyDatabasePrinciplePermissions'
--EXEC [FundReporting].[dbo].[sp_CopyDatabasePrinciplePermissions] 'DOMAIN\ProductionServiceAccount', 'DOMAIN\UATServiceAccount'