USE SL2007
--USE dba 

-- Script to generate user creation and role membership
DECLARE @UserScripts NVARCHAR(MAX) = '';
DECLARE @RoleScripts NVARCHAR(MAX) = '';

-- Generate user creation scripts
SELECT @UserScripts = @UserScripts + 'CREATE USER [' + dp.name + '] FOR LOGIN [' + dp.name + '];' + CHAR(13) + CHAR(10)
FROM sys.database_principals dp
WHERE dp.type IN ('S', 'U', 'G') AND dp.name NOT IN ('dbo', 'guest', 'INFORMATION_SCHEMA', 'sys');

-- Generate role membership scripts
SELECT @RoleScripts = @RoleScripts + 'ALTER ROLE [' + dr.name + '] ADD MEMBER [' + dp.name + '];' + CHAR(13) + CHAR(10)
FROM sys.database_principals dp
JOIN sys.database_role_members drm ON dp.principal_id = drm.member_principal_id
JOIN sys.database_principals dr ON drm.role_principal_id = dr.principal_id
WHERE dp.type IN ('S', 'U', 'G') AND dp.name NOT IN ('dbo', 'guest', 'INFORMATION_SCHEMA', 'sys');

-- Print user creation and role membership scripts
PRINT @UserScripts;
PRINT @RoleScripts;

-- Script to generate permissions
DECLARE @PermissionScripts NVARCHAR(MAX) = '';

SELECT @PermissionScripts = @PermissionScripts + 
    CASE 
        WHEN p.state_desc = 'GRANT' THEN 'GRANT ' 
        WHEN p.state_desc = 'DENY' THEN 'DENY ' 
        WHEN p.state_desc = 'REVOKE' THEN 'REVOKE ' 
    END + p.permission_name + 
    CASE 
        WHEN p.class_desc = 'OBJECT_OR_COLUMN' THEN ' ON [' + OBJECT_NAME(p.major_id) + ']'
        WHEN p.class_desc = 'DATABASE' THEN ' ON DATABASE::[' + DB_NAME() + ']'
        WHEN p.class_desc = 'SCHEMA' THEN ' ON SCHEMA::[' + SCHEMA_NAME(p.major_id) + ']'
        WHEN p.class_desc = 'TYPE' THEN ' ON TYPE::[' + TYPE_NAME(p.major_id) + ']'
        ELSE ''
    END + ' TO [' + dp.name + '];' + CHAR(13) + CHAR(10)
FROM sys.database_permissions p
JOIN sys.database_principals dp ON p.grantee_principal_id = dp.principal_id
WHERE dp.type IN ('S', 'U', 'G') AND dp.name NOT IN ('dbo', 'guest', 'INFORMATION_SCHEMA', 'sys');

-- Print permissions scripts
PRINT @PermissionScripts;