CREATE TABLE #AllRoles(STR_Definition VARCHAR(MAX), STR_Database VARCHAR(255), STR_Product VARCHAR(255))

INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleActivePharmacy role.
  
  Role Name: dbRoleActivePharmacy
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleActivePharmacy''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ActivePos_read','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleCsltUsr role.
  
  Role Name: dbRoleCsltUsr
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleCsltUsr''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''DB'',''GRANT'',''SHOWPLAN'','''',''dbo'',0)
,(''DB'',''GRANT'',''VIEW DEFINITION'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',1)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ActivePos_read','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleDevUsr role.
  
  Role Name: dbRoleDevUsr
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleDevUsr''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''DB'',''GRANT'',''SHOWPLAN'','''',''dbo'',0)
,(''DB'',''GRANT'',''VIEW DEFINITION'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ActivePos_read','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleIttechUsr role.
  
  Role Name: dbRoleIttechUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleIttechUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',1)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','ActivePos_read','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleSupUsr role.
  
  Role Name: dbRoleSupUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleSupUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',1)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','ActivePos_read','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleTPPos role.
  
  Role Name: dbRoleTPPos
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleTPPos''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DDLADMIN'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ActivePos_read','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleActiveConfig role.
  
  Role Name: dbRoleActiveConfig
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleActiveConfig''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''SP'',''GRANT'',''EXECUTE'',''GetApplications'',''dbo'',0)
,(''SP'',''GRANT'',''EXECUTE'',''GetConfigurationDatabaseSchemaVersion'',''dbo'',0)
,(''SP'',''GRANT'',''EXECUTE'',''GetSettings'',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ActivePos_server','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleActivePharmacy role.
  
  Role Name: dbRoleActivePharmacy
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleActivePharmacy''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ActivePos_server','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleCsltUsr role.
  
  Role Name: dbRoleCsltUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleCsltUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''CREATE TABLE'','''',''dbo'',0)
,(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''DB'',''GRANT'',''SHOWPLAN'','''',''dbo'',0)
,(''DB'',''GRANT'',''VIEW DEFINITION'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',1)
,(''SCHEMA'',''GRANT'',''ALTER'',''Entire Schema'',''tmp'',0)
,(''SCHEMA'',''GRANT'',''DELETE'',''Entire Schema'',''tmp'',0)
,(''SCHEMA'',''GRANT'',''EXECUTE'',''Entire Schema'',''tmp'',0)
,(''SCHEMA'',''GRANT'',''INSERT'',''Entire Schema'',''tmp'',0)
,(''SCHEMA'',''GRANT'',''SELECT'',''Entire Schema'',''tmp'',0)
,(''SCHEMA'',''GRANT'',''UPDATE'',''Entire Schema'',''tmp'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','ActivePos_server','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleDevUsr role.
  
  Role Name: dbRoleDevUsr
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleDevUsr''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ActivePos_server','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleIttechUsr role.
  
  Role Name: dbRoleIttechUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleIttechUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''CREATE TABLE'','''',''dbo'',0)
,(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',1)
,(''SCHEMA'',''GRANT'',''ALTER'',''Entire Schema'',''tmp'',0)
,(''SCHEMA'',''GRANT'',''DELETE'',''Entire Schema'',''tmp'',0)
,(''SCHEMA'',''GRANT'',''EXECUTE'',''Entire Schema'',''tmp'',0)
,(''SCHEMA'',''GRANT'',''INSERT'',''Entire Schema'',''tmp'',0)
,(''SCHEMA'',''GRANT'',''SELECT'',''Entire Schema'',''tmp'',0)
,(''SCHEMA'',''GRANT'',''UPDATE'',''Entire Schema'',''tmp'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','ActivePos_server','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleSupUsr role.
  
  Role Name: dbRoleSupUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleSupUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''CREATE TABLE'','''',''dbo'',0)
,(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',1)
,(''SCHEMA'',''GRANT'',''ALTER'',''Entire Schema'',''tmp'',0)
,(''SCHEMA'',''GRANT'',''DELETE'',''Entire Schema'',''tmp'',0)
,(''SCHEMA'',''GRANT'',''EXECUTE'',''Entire Schema'',''tmp'',0)
,(''SCHEMA'',''GRANT'',''INSERT'',''Entire Schema'',''tmp'',0)
,(''SCHEMA'',''GRANT'',''SELECT'',''Entire Schema'',''tmp'',0)
,(''SCHEMA'',''GRANT'',''UPDATE'',''Entire Schema'',''tmp'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','ActivePos_server','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleTPPos role.
  
  Role Name: dbRoleTPPos
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleTPPos''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DDLADMIN'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ActivePos_server','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleActiveConfig role.
  
  Role Name: dbRoleActiveConfig
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleActiveConfig''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''SP'',''GRANT'',''EXECUTE'',''GetApplications'',''dbo'',0)
,(''SP'',''GRANT'',''EXECUTE'',''GetConfigurationDatabaseSchemaVersion'',''dbo'',0)
,(''SP'',''GRANT'',''EXECUTE'',''GetSettings'',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ActivePos_write','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleActivePharmacy role.
  
  Role Name: dbRoleActivePharmacy
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleActivePharmacy''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ActivePos_write','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleCsltUsr role.
  
  Role Name: dbRoleCsltUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleCsltUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''DB'',''GRANT'',''SHOWPLAN'','''',''dbo'',0)
,(''DB'',''GRANT'',''VIEW DEFINITION'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',1)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','ActivePos_write','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleDevUsr role.
  
  Role Name: dbRoleDevUsr
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleDevUsr''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''DB'',''GRANT'',''SHOWPLAN'','''',''dbo'',0)
,(''DB'',''GRANT'',''VIEW DEFINITION'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ActivePos_write','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleIttechUsr role.
  
  Role Name: dbRoleIttechUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleIttechUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',1)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','ActivePos_write','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleSupUsr role.
  
  Role Name: dbRoleSupUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleSupUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',1)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','ActivePos_write','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleTPPos role.
  
  Role Name: dbRoleTPPos
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleTPPos''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DDLADMIN'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ActivePos_write','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleActiveConfig role.
  
  Role Name: dbRoleActiveConfig
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleActiveConfig''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''SP'',''GRANT'',''EXECUTE'',''GetApplications'',''cfg'',0)
,(''SP'',''GRANT'',''EXECUTE'',''GetConfigurationDatabaseSchemaVersion'',''cfg'',0)
,(''SP'',''GRANT'',''EXECUTE'',''GetSettings'',''cfg'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ActiveSystemClient','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleActivePharmacy role.
  
  Role Name: dbRoleActivePharmacy
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleActivePharmacy''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ActiveSystemClient','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleCsltUsr role.
  
  Role Name: dbRoleCsltUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleCsltUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''DB'',''GRANT'',''SHOWPLAN'','''',''dbo'',0)
,(''DB'',''GRANT'',''VIEW DEFINITION'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',1)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','ActiveSystemClient','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleDevUsr role.
  
  Role Name: dbRoleDevUsr
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleDevUsr''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''DB'',''GRANT'',''SHOWPLAN'','''',''dbo'',0)
,(''DB'',''GRANT'',''VIEW DEFINITION'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ActiveSystemClient','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleIttechUsr role.
  
  Role Name: dbRoleIttechUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleIttechUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',1)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','ActiveSystemClient','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleSupUsr role.
  
  Role Name: dbRoleSupUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleSupUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',1)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','ActiveSystemClient','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleActiveConfig role.
  
  Role Name: dbRoleActiveConfig
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleActiveConfig''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''SP'',''GRANT'',''EXECUTE'',''GetApplications'',''cfg'',0)
,(''SP'',''GRANT'',''EXECUTE'',''GetConfigurationDatabaseSchemaVersion'',''cfg'',0)
,(''SP'',''GRANT'',''EXECUTE'',''GetSettings'',''cfg'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ActiveSystemServer','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleActivePharmacy role.
  
  Role Name: dbRoleActivePharmacy
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleActivePharmacy''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ActiveSystemServer','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleCsltUsr role.
  
  Role Name: dbRoleCsltUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleCsltUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''DB'',''GRANT'',''SHOWPLAN'','''',''dbo'',0)
,(''DB'',''GRANT'',''VIEW DEFINITION'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',1)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','ActiveSystemServer','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleDevUsr role.
  
  Role Name: dbRoleDevUsr
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleDevUsr''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''DB'',''GRANT'',''SHOWPLAN'','''',''dbo'',0)
,(''DB'',''GRANT'',''VIEW DEFINITION'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ActiveSystemServer','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleIttechUsr role.
  
  Role Name: dbRoleIttechUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleIttechUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',1)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','ActiveSystemServer','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleSupUsr role.
  
  Role Name: dbRoleSupUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleSupUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',1)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','ActiveSystemServer','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleTPPos role.
  
  Role Name: dbRoleTPPos
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleTPPos''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DDLADMIN'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ActiveSystemServer','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleActivePharmacy role.
  
  Role Name: dbRoleActivePharmacy
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleActivePharmacy''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','Arizona','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleArizonaCASH role.
  
  Role Name: dbRoleArizonaCASH
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleArizonaCASH''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''SP'',''GRANT'',''EXECUTE'',''aps_Check_Database_Version'',''dbo'',0)
,(''SP'',''GRANT'',''EXECUTE'',''sp_bmc_Bmc_Applic_Default'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Currency_Rate'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Document_line'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Item'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''item_key'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Item_text'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Language'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''PH_item'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''PH_refund_code'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Sales_Tax_Rate'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Stock_trans_effective_cost'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Stock_transaction'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Stock_transaction_master'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''TT_GetNext_ID'',''dbo'',0)
,(''TABLE'',''GRANT'',''UPDATE'',''TT_GetNext_ID'',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','Arizona','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleAtlas role.
  
  Role Name: dbRoleAtlas
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleAtlas''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''SCHEMA'',''GRANT'',''DELETE'',''Entire Schema'',''atl'',0)
,(''SCHEMA'',''GRANT'',''EXECUTE'',''Entire Schema'',''atl'',0)
,(''SCHEMA'',''GRANT'',''INSERT'',''Entire Schema'',''atl'',0)
,(''SCHEMA'',''GRANT'',''SELECT'',''Entire Schema'',''atl'',0)
,(''SCHEMA'',''GRANT'',''UPDATE'',''Entire Schema'',''atl'',0)
,(''SP'',''GRANT'',''EXECUTE'',''aps_Document_Flow'',''dbo'',0)
,(''SP'',''GRANT'',''EXECUTE'',''sp_bmc_Bmc_Applic_Default'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Account_link'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Address'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Address_key'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Bmc_application_default'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Bmc_application_key'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Bmc_user_profile'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Customer'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Document_header'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Document_line'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Document_line_link'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Document_type'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Entry'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Entry_reconciliation'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Item_key'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Organizational_unit'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''OU_store_history'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''PH_insurance'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''PH_insurance_card'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''PH_insurance_plan'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''PH_prescriber'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''PH_prescription_header'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''PH_prescription_line'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''PHGD_AC'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Predefined_entry'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Sales_tax_code'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Sales_tax_rate'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Stock_transaction_master'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Title_text'',''dbo'',0)
,(''TABLE'',''GRANT'',''UPDATE'',''Document_header'',''dbo'',0)
,(''TABLE'',''GRANT'',''UPDATE'',''Document_line'',''dbo'',0)
,(''TABLE'',''GRANT'',''UPDATE'',''PH_prescription_line'',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','Arizona','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleCsltUsr role.
  
  Role Name: dbRoleCsltUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleCsltUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''DB'',''GRANT'',''SHOWPLAN'','''',''dbo'',0)
,(''DB'',''GRANT'',''VIEW DEFINITION'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',1)
,(''TABLE'',''DENY'',''DELETE'',''DocumentSignature'',''wkl'',0)
,(''TABLE'',''DENY'',''UPDATE'',''DocumentSignature'',''wkl'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','Arizona','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleDataMonitoring role.
  
  Role Name: dbRoleDataMonitoring
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleDataMonitoring''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''SCHEMA'',''GRANT'',''DELETE'',''Entire Schema'',''dam'',0)
,(''SCHEMA'',''GRANT'',''EXECUTE'',''Entire Schema'',''dam'',0)
,(''SCHEMA'',''GRANT'',''INSERT'',''Entire Schema'',''dam'',0)
,(''SCHEMA'',''GRANT'',''SELECT'',''Entire Schema'',''dam'',0)
,(''SCHEMA'',''GRANT'',''UPDATE'',''Entire Schema'',''dam'',0)
,(''SP'',''GRANT'',''EXECUTE'',''sp_bmc_Bmc_Applic_Default'',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','Arizona','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleDevUsr role.
  
  Role Name: dbRoleDevUsr
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleDevUsr''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''DB'',''GRANT'',''SHOWPLAN'','''',''dbo'',0)
,(''DB'',''GRANT'',''VIEW DEFINITION'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)
,(''SP'',''GRANT'',''ALTER'',''%PH_Invoice%'',''dbo'',0)
,(''SP'',''GRANT'',''ALTER'',''%PH_Streamfact%'',''dbo'',0)
,(''TABLE'',''DENY'',''SELECT'',''DocumentSignature'',''wkl'',0)
,(''TABLE'',''DENY'',''UPDATE'',''DocumentSignature'',''wkl'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Document_header'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Document_line'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''PH_prescription_line'',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','Arizona','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleGcStock role.
  
  Role Name: dbRoleGcStock
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleGcStock''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''SP'',''GRANT'',''EXECUTE'',''aps_Galenicare_Inventory_Detail'',''dbo'',0)
,(''SP'',''GRANT'',''EXECUTE'',''aps_PHID_Create_1_13'',''dbo'',0)
,(''SP'',''GRANT'',''EXECUTE'',''aps_PHID_Load'',''dbo'',0)
,(''SP'',''GRANT'',''EXECUTE'',''aps_TT_Physical_Inventory_Detail_Load'',''dbo'',0)
,(''SP'',''GRANT'',''EXECUTE'',''sp_bmc_PHID_Create'',''dbo'',0)
,(''SP'',''GRANT'',''EXECUTE'',''sp_bmc_PHID_Update'',''dbo'',0)
,(''SP'',''GRANT'',''EXECUTE'',''sp_bmc_PHIM_Processing'',''dbo'',0)
,(''SP'',''GRANT'',''EXECUTE'',''sp_bmc_Physical_Inv_Detail'',''dbo'',0)
,(''SP'',''GRANT'',''EXECUTE'',''sp_bmc_Physical_Inv_Master'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''v_Galenicare_OU_List'',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','Arizona','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleGroupRepetition role.
  
  Role Name: dbRoleGroupRepetition
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleGroupRepetition''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''SP'',''GRANT'',''EXECUTE'',''aps_Get_Sales_Detail'',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','Arizona','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleIttechUsr role.
  
  Role Name: dbRoleIttechUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleIttechUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',1)
,(''TABLE'',''DENY'',''DELETE'',''DocumentSignature'',''wkl'',0)
,(''TABLE'',''DENY'',''UPDATE'',''DocumentSignature'',''wkl'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','Arizona','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleSupUsr role.
  
  Role Name: dbRoleSupUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleSupUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',1)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','Arizona','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleSyncAccountingExtraction role.
  
  Role Name: dbRoleSyncAccountingExtraction
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleSyncAccountingExtraction''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''DB'',''GRANT'',''VIEW DEFINITION'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','Arizona','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleTPPos role.
  
  Role Name: dbRoleTPPos
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleTPPos''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''TABLE'',''GRANT'',''INSERT'',''DocumentSignature'',''wkl'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Bmc_application_default'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Bmc_application_key'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''DocumentSignature'',''wkl'',0)
,(''TABLE'',''GRANT'',''SELECT'',''IT_config_setting'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Organizational_unit'',''dbo'',0)
,(''TABLE'',''GRANT'',''UPDATE'',''Bmc_application_default'',''dbo'',0)
,(''TABLE'',''GRANT'',''UPDATE'',''Bmc_application_key'',''dbo'',0)
,(''TABLE'',''GRANT'',''UPDATE'',''IT_config_setting'',''dbo'',0)
,(''TABLE'',''GRANT'',''UPDATE'',''Organizational_unit'',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','Arizona','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleTriapharmChangeTracking role.
  
  Role Name: dbRoleTriapharmChangeTracking
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleTriapharmChangeTracking''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''SP'',''GRANT'',''EXECUTE'',''SP_TRIABI_GetData'',''dbo'',0)
,(''SP'',''GRANT'',''EXECUTE'',''SP_TRIABI_GetMeta'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Address'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Address_category'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Address_category_text'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Address_criteria'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Address_group'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Address_group_text'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Address_key'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Address_link'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Address_type'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Bmc_application_default'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Bmc_application_key'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Bmc_user_profile'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Brand'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Brand_OU_link'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Brand_text'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Change_tracking_monitor'',''upd'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Company'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Country'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Criteria'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Criteria_text'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Criteria_type'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Criteria_type_text'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''DBA_change_tracking'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''DiscountVoucher'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''DiscountVoucherCondition'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''DiscountVoucherText'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''DL_Posology'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Document_header'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Document_line'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Document_line_link'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Document_type'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Document_type_text'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Employment_contract'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Employment_contract_history'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Fiscal_year'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Fixed_price'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''GoodsReceipt'',''wkl'',0)
,(''TABLE'',''GRANT'',''SELECT'',''GoodsReceiptLine'',''wkl'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Item'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Item_context'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Item_context_status'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Item_context_status_text'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Item_criteria'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Item_dispatch_header'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Item_dispatch_line'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Item_family'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Item_family_text'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Item_group'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Item_group_text'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Item_inventory'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Item_key'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''item_link'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Item_purchase'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Item_quantity'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Item_relation_info'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Item_sale'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Item_seasonal_stock_info'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Item_shipping'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Item_standard_cost'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Item_status_history'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Item_text'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Item_unit_conversion'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Job_function'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Job_function_text'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Language'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''LORE_item_ABC_code'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''LORE_supplying_procedure'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Manufacturer'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''MissedSale'',''wkl'',0)
,(''TABLE'',''GRANT'',''SELECT'',''OrderRequest'',''wkl'',0)
,(''TABLE'',''GRANT'',''SELECT'',''OrderRequestLine'',''wkl'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Organizational_unit'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''OU_store_history'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''OU_store_type'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''PH_insurance'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''PH_insurance_card'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''PH_insurance_plan'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''PH_insurance_recommendation'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''PH_item'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''PH_OICM_code'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''PH_OICM_code_text'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''PH_organizational_unit'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''PH_patient'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''PH_physician'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''PH_prescriber'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''PH_prescription_header'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''PH_prescription_line'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''PH_product'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''PH_qualification'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''PH_refund_code'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''PH_refund_code_text'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''PHGD_AC'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''PHGD_ACBARCODE'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''PHGD_ACCHAIN'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''PHGD_ACMED'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''PHGD_CODES'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''PHGD_CODETXT'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Predefined_entry'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Price_code'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Price_modifier'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Product_line'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Product_line_text'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Profit_cost_center'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Profit_cost_center_key'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''PurchaseReturn'',''wkl'',0)
,(''TABLE'',''GRANT'',''SELECT'',''PurchaseReturnLine'',''wkl'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Sales_tax_rate'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Standard_text'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Standard_text_text'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Status_text'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Subsidiary'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Supplier'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Tariff_type'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''VIP_card'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''VIP_card_type'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''VIP_card_type_link'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''WebShopStatusQueue'',''AP'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Address'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Address_category'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Address_category_text'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Address_criteria'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Address_group'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Address_group_text'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Address_key'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Address_link'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Address_type'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Bmc_application_default'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Bmc_application_key'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Bmc_user_profile'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Brand'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Brand_OU_link'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Brand_text'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Change_tracking_monitor'',''upd'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Company'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Country'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Criteria'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Criteria_text'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Criteria_type'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Criteria_type_text'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''DBA_change_tracking'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''DiscountVoucher'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''DiscountVoucherCondition'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''DiscountVoucherText'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''DL_Posology'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Document_header'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Document_line'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Document_line_link'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Document_type'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Document_type_text'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Employment_contract'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Employment_contract_history'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Fiscal_year'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Fixed_price'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''GoodsReceipt'',''wkl'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''GoodsReceiptLine'',''wkl'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Item'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Item_context'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Item_context_status'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Item_context_status_text'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Item_criteria'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Item_dispatch_header'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Item_dispatch_line'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Item_family'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Item_family_text'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Item_group'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Item_group_text'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Item_inventory'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Item_key'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''item_link'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Item_purchase'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Item_quantity'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Item_relation_info'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Item_sale'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Item_seasonal_stock_info'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Item_shipping'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Item_standard_cost'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Item_status_history'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Item_text'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Item_unit_conversion'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Job_function'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Job_function_text'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Language'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''LORE_item_ABC_code'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''LORE_supplying_procedure'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Manufacturer'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''MissedSale'',''wkl'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''OrderRequest'',''wkl'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''OrderRequestLine'',''wkl'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Organizational_unit'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''OU_store_history'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''OU_store_type'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''PH_insurance'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''PH_insurance_card'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''PH_insurance_plan'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''PH_insurance_recommendation'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''PH_item'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''PH_OICM_code'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''PH_OICM_code_text'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''PH_organizational_unit'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''PH_patient'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''PH_physician'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''PH_prescriber'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''PH_prescription_header'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''PH_prescription_line'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''PH_product'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''PH_qualification'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''PH_refund_code'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''PH_refund_code_text'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''PHGD_AC'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''PHGD_ACBARCODE'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''PHGD_ACCHAIN'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''PHGD_ACMED'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''PHGD_CODES'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''PHGD_CODETXT'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Predefined_entry'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Price_code'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Price_modifier'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Product_line'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Product_line_text'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Profit_cost_center'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Profit_cost_center_key'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''PurchaseReturn'',''wkl'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''PurchaseReturnLine'',''wkl'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Sales_tax_rate'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Standard_text'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Standard_text_text'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Status_text'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Subsidiary'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Supplier'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''Tariff_type'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''VIP_card'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''VIP_card_type'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''VIP_card_type_link'',''dbo'',0)
,(''TABLE'',''GRANT'',''VIEW CHANGE TRACKING'',''WebShopStatusQueue'',''AP'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','Arizona','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleTriapharmCounter role.
  
  Role Name: dbRoleTriapharmCounter
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleTriapharmCounter''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''SP'',''GRANT'',''EXECUTE'',''aps_Document_Counter_1'',''dbo'',0)
,(''SP'',''GRANT'',''EXECUTE'',''aps_GetNextID'',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','Arizona','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleTriapharmUser role.
  
  Role Name: dbRoleTriapharmUser
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleTriapharmUser''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''DB'',''GRANT'',''VIEW DEFINITION'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','Arizona','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleActivePharmacy role.
  
  Role Name: dbRoleActivePharmacy
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleActivePharmacy''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ArizonaCASH','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleArizonaCASH role.
  
  Role Name: dbRoleArizonaCASH
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleArizonaCASH''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)
,(''TABLE'',''GRANT'',''ALTER'',''CR_cash_report_header'',''dbo'',0)
,(''TABLE'',''GRANT'',''ALTER'',''CR_internal_operation'',''dbo'',0)
,(''TABLE'',''GRANT'',''ALTER'',''CR_item_key'',''dbo'',0)
,(''TABLE'',''GRANT'',''ALTER'',''CR_operation'',''dbo'',0)
,(''TABLE'',''GRANT'',''ALTER'',''CR_point_of_sale'',''dbo'',0)
,(''TABLE'',''GRANT'',''ALTER'',''CR_POS_data'',''dbo'',0)
,(''TABLE'',''GRANT'',''ALTER'',''CR_print_report'',''dbo'',0)
,(''TABLE'',''GRANT'',''ALTER'',''CR_sales_header'',''dbo'',0)
,(''TABLE'',''GRANT'',''ALTER'',''CR_sales_item'',''dbo'',0)
,(''TABLE'',''GRANT'',''ALTER'',''CR_sales_operation'',''dbo'',0)
,(''TABLE'',''GRANT'',''ALTER'',''CR_sales_type'',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ArizonaCASH','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleAtlas role.
  
  Role Name: dbRoleAtlas
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleAtlas''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''TABLE'',''GRANT'',''SELECT'',''CR_operation'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''CR_sales_header'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''CR_sales_operation'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''CR_sales_type'',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ArizonaCASH','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleCsltUsr role.
  
  Role Name: dbRoleCsltUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleCsltUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''DB'',''GRANT'',''SHOWPLAN'','''',''dbo'',0)
,(''DB'',''GRANT'',''VIEW DEFINITION'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',1)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','ArizonaCASH','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleDevUsr role.
  
  Role Name: dbRoleDevUsr
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleDevUsr''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''DB'',''GRANT'',''SHOWPLAN'','''',''dbo'',0)
,(''DB'',''GRANT'',''VIEW DEFINITION'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ArizonaCASH','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleIttechUsr role.
  
  Role Name: dbRoleIttechUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleIttechUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',1)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','ArizonaCASH','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleSupUsr role.
  
  Role Name: dbRoleSupUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleSupUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',1)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','ArizonaCASH','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleSyncAccountingExtraction role.
  
  Role Name: dbRoleSyncAccountingExtraction
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleSyncAccountingExtraction''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''DB'',''GRANT'',''VIEW DEFINITION'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ArizonaCASH','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleTPPos role.
  
  Role Name: dbRoleTPPos
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleTPPos''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DDLADMIN'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ArizonaCASH','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleTriapharmUser role.
  
  Role Name: dbRoleTriapharmUser
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleTriapharmUser''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ArizonaCASH','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleCsltUsr role.
  
  Role Name: dbRoleCsltUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleCsltUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',1)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','ArizonaCUST','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleDevUsr role.
  
  Role Name: dbRoleDevUsr
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleDevUsr''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''DB'',''GRANT'',''SHOWPLAN'','''',''dbo'',0)
,(''DB'',''GRANT'',''VIEW DEFINITION'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ArizonaCUST','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleIttechUsr role.
  
  Role Name: dbRoleIttechUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleIttechUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',1)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','ArizonaCUST','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleSupUsr role.
  
  Role Name: dbRoleSupUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleSupUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',1)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','ArizonaCUST','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleSyncAccountingExtraction role.
  
  Role Name: dbRoleSyncAccountingExtraction
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleSyncAccountingExtraction''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''DB'',''GRANT'',''VIEW DEFINITION'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ArizonaCUST','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleCsltUsr role.
  
  Role Name: dbRoleCsltUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleCsltUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',1)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','ArizonaLD','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleDevUsr role.
  
  Role Name: dbRoleDevUsr
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleDevUsr''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''DB'',''GRANT'',''SHOWPLAN'','''',''dbo'',0)
,(''DB'',''GRANT'',''VIEW DEFINITION'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ArizonaLD','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleIttechUsr role.
  
  Role Name: dbRoleIttechUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleIttechUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',1)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','ArizonaLD','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleSupUsr role.
  
  Role Name: dbRoleSupUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleSupUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',1)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','ArizonaLD','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleCsltUsr role.
  
  Role Name: dbRoleCsltUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleCsltUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',1)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','ArizonaTest','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleDevUsr role.
  
  Role Name: dbRoleDevUsr
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleDevUsr''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ArizonaTest','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleIttechUsr role.
  
  Role Name: dbRoleIttechUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleIttechUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',1)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','ArizonaTest','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleSupUsr role.
  
  Role Name: dbRoleSupUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleSupUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',1)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','ArizonaTest','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleCsltUsr role.
  
  Role Name: dbRoleCsltUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleCsltUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''REPLMONITOR'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''REPLMONITOR'','''',''dbo'',1)
,(''TABLE'',''GRANT'',''SELECT'',''MSdistribution_agents'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''MSdistribution_agents'',''dbo'',1)
,(''TABLE'',''GRANT'',''SELECT'',''MSdistribution_history'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''MSdistribution_history'',''dbo'',1)
,(''TABLE'',''GRANT'',''SELECT'',''MSrepl_commands'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''MSrepl_commands'',''dbo'',1)
,(''TABLE'',''GRANT'',''SELECT'',''MSsubscriptions'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''MSsubscriptions'',''dbo'',1)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','distribution','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleDevUsr role.
  
  Role Name: dbRoleDevUsr
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleDevUsr''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''REPLMONITOR'','''',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''MSdistribution_agents'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''MSdistribution_history'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''MSrepl_commands'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''MSsubscriptions'',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','distribution','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleIttechUsr role.
  
  Role Name: dbRoleIttechUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleIttechUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',1)
,(''ROLE'',''GRANT'',''REPLMONITOR'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''REPLMONITOR'','''',''dbo'',1)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','distribution','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleSupUsr role.
  
  Role Name: dbRoleSupUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleSupUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''REPLMONITOR'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''REPLMONITOR'','''',''dbo'',1)
,(''TABLE'',''GRANT'',''SELECT'',''MSdistribution_agents'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''MSdistribution_agents'',''dbo'',1)
,(''TABLE'',''GRANT'',''SELECT'',''MSdistribution_history'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''MSdistribution_history'',''dbo'',1)
,(''TABLE'',''GRANT'',''SELECT'',''MSrepl_commands'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''MSrepl_commands'',''dbo'',1)
,(''TABLE'',''GRANT'',''SELECT'',''MSsubscriptions'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''MSsubscriptions'',''dbo'',1)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','distribution','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleTPPos role.
  
  Role Name: dbRoleTPPos
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleTPPos''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DDLADMIN'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','distribution','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleCsltUsr role.
  
  Role Name: dbRoleCsltUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleCsltUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''CREATE TABLE'','''',''dbo'',0)
,(''DB'',''GRANT'',''CREATE TABLE'','''',''dbo'',1)
,(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',1)
,(''DB'',''GRANT'',''VIEW DEFINITION'','''',''dbo'',0)
,(''DB'',''GRANT'',''VIEW DEFINITION'','''',''dbo'',1)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',1)
,(''SCHEMA'',''GRANT'',''ALTER'',''Entire Schema'',''tmp'',0)
,(''SCHEMA'',''GRANT'',''ALTER'',''Entire Schema'',''tmp'',1)
,(''SCHEMA'',''GRANT'',''DELETE'',''Entire Schema'',''tmp'',0)
,(''SCHEMA'',''GRANT'',''DELETE'',''Entire Schema'',''tmp'',1)
,(''SCHEMA'',''GRANT'',''EXECUTE'',''Entire Schema'',''tmp'',0)
,(''SCHEMA'',''GRANT'',''EXECUTE'',''Entire Schema'',''tmp'',1)
,(''SCHEMA'',''GRANT'',''INSERT'',''Entire Schema'',''tmp'',0)
,(''SCHEMA'',''GRANT'',''INSERT'',''Entire Schema'',''tmp'',1)
,(''SCHEMA'',''GRANT'',''SELECT'',''Entire Schema'',''tmp'',0)
,(''SCHEMA'',''GRANT'',''SELECT'',''Entire Schema'',''tmp'',1)
,(''SCHEMA'',''GRANT'',''UPDATE'',''Entire Schema'',''tmp'',0)
,(''SCHEMA'',''GRANT'',''UPDATE'',''Entire Schema'',''tmp'',1)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','HCITools','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleDataMonitoring role.
  
  Role Name: dbRoleDataMonitoring
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleDataMonitoring''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''SCHEMA'',''GRANT'',''DELETE'',''Entire Schema'',''dam'',0)
,(''SCHEMA'',''GRANT'',''EXECUTE'',''Entire Schema'',''dam'',0)
,(''SCHEMA'',''GRANT'',''INSERT'',''Entire Schema'',''dam'',0)
,(''SCHEMA'',''GRANT'',''SELECT'',''Entire Schema'',''dam'',0)
,(''SCHEMA'',''GRANT'',''UPDATE'',''Entire Schema'',''dam'',0)
,(''SP'',''GRANT'',''EXECUTE'',''GetAllJobsInformations'',''mon'',0)
,(''SP'',''GRANT'',''EXECUTE'',''GetJobStepState'',''mon'',0)
,(''TABLE'',''GRANT'',''DELETE'',''HCI_PARAMS'',''dbo'',0)
,(''TABLE'',''GRANT'',''INSERT'',''HCI_PARAMS'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''HCI_PARAMS'',''dbo'',0)
,(''TABLE'',''GRANT'',''UPDATE'',''HCI_PARAMS'',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','HCITools','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleDevUsr role.
  
  Role Name: dbRoleDevUsr
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleDevUsr''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''CREATE TABLE'','''',''dbo'',0)
,(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''DB'',''GRANT'',''SHOWPLAN'','''',''dbo'',0)
,(''DB'',''GRANT'',''VIEW DEFINITION'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''SCHEMA'',''GRANT'',''ALTER'',''Entire Schema'',''tmp'',0)
,(''SCHEMA'',''GRANT'',''DELETE'',''Entire Schema'',''tmp'',0)
,(''SCHEMA'',''GRANT'',''EXECUTE'',''Entire Schema'',''tmp'',0)
,(''SCHEMA'',''GRANT'',''INSERT'',''Entire Schema'',''tmp'',0)
,(''SCHEMA'',''GRANT'',''SELECT'',''Entire Schema'',''tmp'',0)
,(''SCHEMA'',''GRANT'',''UPDATE'',''Entire Schema'',''tmp'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','HCITools','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleIttechUsr role.
  
  Role Name: dbRoleIttechUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleIttechUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''CREATE TABLE'','''',''dbo'',0)
,(''DB'',''GRANT'',''CREATE TABLE'','''',''dbo'',1)
,(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',1)
,(''DB'',''GRANT'',''VIEW DEFINITION'','''',''dbo'',0)
,(''DB'',''GRANT'',''VIEW DEFINITION'','''',''dbo'',1)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',1)
,(''SCHEMA'',''GRANT'',''ALTER'',''Entire Schema'',''tmp'',0)
,(''SCHEMA'',''GRANT'',''ALTER'',''Entire Schema'',''tmp'',1)
,(''SCHEMA'',''GRANT'',''DELETE'',''Entire Schema'',''tmp'',0)
,(''SCHEMA'',''GRANT'',''DELETE'',''Entire Schema'',''tmp'',1)
,(''SCHEMA'',''GRANT'',''EXECUTE'',''Entire Schema'',''tmp'',0)
,(''SCHEMA'',''GRANT'',''EXECUTE'',''Entire Schema'',''tmp'',1)
,(''SCHEMA'',''GRANT'',''INSERT'',''Entire Schema'',''tmp'',0)
,(''SCHEMA'',''GRANT'',''INSERT'',''Entire Schema'',''tmp'',1)
,(''SCHEMA'',''GRANT'',''SELECT'',''Entire Schema'',''tmp'',0)
,(''SCHEMA'',''GRANT'',''SELECT'',''Entire Schema'',''tmp'',1)
,(''SCHEMA'',''GRANT'',''UPDATE'',''Entire Schema'',''tmp'',0)
,(''SCHEMA'',''GRANT'',''UPDATE'',''Entire Schema'',''tmp'',1)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','HCITools','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleNagiosMonitoring role.
  
  Role Name: dbRoleNagiosMonitoring
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleNagiosMonitoring''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''TABLE'',''GRANT'',''SELECT'',''v_ReplicationCheck'',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','HCITools','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleSSRSMonitoring role.
  
  Role Name: dbRoleSSRSMonitoring
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleSSRSMonitoring''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''SP'',''GRANT'',''EXECUTE'',''mon_Get_Counters_History'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''Monitoring_%'',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','HCITools','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleSupUsr role.
  
  Role Name: dbRoleSupUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleSupUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''CREATE TABLE'','''',''dbo'',0)
,(''DB'',''GRANT'',''CREATE TABLE'','''',''dbo'',1)
,(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',1)
,(''DB'',''GRANT'',''VIEW DEFINITION'','''',''dbo'',0)
,(''DB'',''GRANT'',''VIEW DEFINITION'','''',''dbo'',1)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',1)
,(''SCHEMA'',''GRANT'',''ALTER'',''Entire Schema'',''tmp'',0)
,(''SCHEMA'',''GRANT'',''ALTER'',''Entire Schema'',''tmp'',1)
,(''SCHEMA'',''GRANT'',''DELETE'',''Entire Schema'',''tmp'',0)
,(''SCHEMA'',''GRANT'',''DELETE'',''Entire Schema'',''tmp'',1)
,(''SCHEMA'',''GRANT'',''EXECUTE'',''Entire Schema'',''tmp'',0)
,(''SCHEMA'',''GRANT'',''EXECUTE'',''Entire Schema'',''tmp'',1)
,(''SCHEMA'',''GRANT'',''INSERT'',''Entire Schema'',''tmp'',0)
,(''SCHEMA'',''GRANT'',''INSERT'',''Entire Schema'',''tmp'',1)
,(''SCHEMA'',''GRANT'',''SELECT'',''Entire Schema'',''tmp'',0)
,(''SCHEMA'',''GRANT'',''SELECT'',''Entire Schema'',''tmp'',1)
,(''SCHEMA'',''GRANT'',''UPDATE'',''Entire Schema'',''tmp'',0)
,(''SCHEMA'',''GRANT'',''UPDATE'',''Entire Schema'',''tmp'',1)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','HCITools','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleAtlas role.
  
  Role Name: dbRoleAtlas
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleAtlas''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''TABLE'',''GRANT'',''SELECT'',''InstanceContext'',''cfg'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','master','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleSyncAccountingExtraction role.
  
  Role Name: dbRoleSyncAccountingExtraction
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleSyncAccountingExtraction''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''TABLE'',''GRANT'',''SELECT'',''Identity'',''cfg'',0)
,(''TABLE'',''GRANT'',''SELECT'',''InstanceContext'',''cfg'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','master','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleTPPos role.
  
  Role Name: dbRoleTPPos
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleTPPos''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''DB'',''GRANT'',''EXECUTE'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DDLADMIN'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','master','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleCsltUsr role.
  
  Role Name: dbRoleCsltUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleCsltUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DATABASEMAILUSERROLE'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DATABASEMAILUSERROLE'','''',''dbo'',1)
,(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',1)
,(''ROLE'',''GRANT'',''SQLAGENTOPERATORROLE'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''SQLAGENTOPERATORROLE'','''',''dbo'',1)
,(''TABLE'',''GRANT'',''SELECT'',''sysjobs'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''sysjobsteps'',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','msdb','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleDataMonitoring role.
  
  Role Name: dbRoleDataMonitoring
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleDataMonitoring''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''SP'',''GRANT'',''EXECUTE'',''agent_datetime'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''sysjobactivity'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''sysjobhistory'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''sysjobs'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''sysjobschedules'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''sysschedules'',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','msdb','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleDevUsr role.
  
  Role Name: dbRoleDevUsr
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleDevUsr''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DATABASEMAILUSERROLE'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''SQLAGENTOPERATORROLE'','''',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''sysjobs'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''sysjobsteps'',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','msdb','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleIttechUsr role.
  
  Role Name: dbRoleIttechUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleIttechUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DATABASEMAILUSERROLE'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',1)
,(''ROLE'',''GRANT'',''DB_DATAWRITER'','''',''dbo'',1)
,(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',1)
,(''ROLE'',''GRANT'',''SQLAGENTOPERATORROLE'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','msdb','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleSupUsr role.
  
  Role Name: dbRoleSupUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleSupUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DATABASEMAILUSERROLE'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DATABASEMAILUSERROLE'','''',''dbo'',1)
,(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',1)
,(''ROLE'',''GRANT'',''SQLAGENTOPERATORROLE'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''SQLAGENTOPERATORROLE'','''',''dbo'',1)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','msdb','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleTPPos role.
  
  Role Name: dbRoleTPPos
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleTPPos''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_DDLADMIN'','''',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''sysjobactivity'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''sysjobs'',''dbo'',0)
,(''TABLE'',''GRANT'',''SELECT'',''sysjobs_view'',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','msdb','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleCsltUsr role.
  
  Role Name: dbRoleCsltUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleCsltUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',1)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','Symbiose','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleDevUsr role.
  
  Role Name: dbRoleDevUsr
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleDevUsr''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','Symbiose','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleIttechUsr role.
  
  Role Name: dbRoleIttechUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleIttechUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',1)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','Symbiose','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleSupUsr role.
  
  Role Name: dbRoleSupUsr
  TEMPLATE: N2 and PROD
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Type            varchar(6),
        @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleSupUsr''
SET @Command = ''''

SELECT @Type = [Type] FROM [master].[cfg].[InstanceContext]

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',0)
,(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',1)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
IF @Type = ''DEVE''
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 1

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
       END
     END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN
    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END
ELSE
BEGIN

  DECLARE SecurablesCurs CURSOR FOR 
  SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
  FROM #Securables
  WHERE N2 = 0

  OPEN SecurablesCurs
  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  WHILE @@FETCH_STATUS = 0
  BEGIN

    IF @typeofobject = ''DB''
    BEGIN
	  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	  BEGIN
        SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
      END
    END

    IF @typeofobject = ''SCHEMA''
    BEGIN
    SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
    END

    IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
    BEGIN

    IF @objectname like ''%[%]%''
    BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

    END
    ELSE
    BEGIN

      SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
    END
  END

  IF @typeofobject = ''ASSEMBLIES''
  BEGIN
    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject = ''ROLE''
  BEGIN
    SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
  END

  FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
  END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

END

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command

/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole','Symbiose','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleDevUsr role.
  
  Role Name: dbRoleDevUsr
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleDevUsr''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_OWNER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','Golabo','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleGaia role.
  
  Role Name: dbRoleGaia
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleGaia''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','Arizona','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleQAtesters role.
  
  Role Name: dbRoleQAtesters
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleQAtesters''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ActivePos_read','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleQAtesters role.
  
  Role Name: dbRoleQAtesters
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleQAtesters''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ActivePos_server','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleQAtesters role.
  
  Role Name: dbRoleQAtesters
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleQAtesters''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ActivePos_write','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleQAtesters role.
  
  Role Name: dbRoleQAtesters
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleQAtesters''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ActiveSystemClient','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleQAtesters role.
  
  Role Name: dbRoleQAtesters
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleQAtesters''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ActiveSystemServer','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleQAtesters role.
  
  Role Name: dbRoleQAtesters
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleQAtesters''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','Arizona','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleQAtesters role.
  
  Role Name: dbRoleQAtesters
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleQAtesters''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ArizonaCASH','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleQAtesters role.
  
  Role Name: dbRoleQAtesters
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleQAtesters''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ArizonaCUST','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleQAtesters role.
  
  Role Name: dbRoleQAtesters
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleQAtesters''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ArizonaLD','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleTPSSIS role.
  
  Role Name: dbRoleTPSSIS
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleTPSSIS''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','Arizona','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRolePOUsr role.
  
  Role Name: dbRolePOUsr
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRolePOUsr''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ActivePos_read','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRolePOUsr role.
  
  Role Name: dbRolePOUsr
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRolePOUsr''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ActivePos_server','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRolePOUsr role.
  
  Role Name: dbRolePOUsr
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRolePOUsr''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ActivePos_write','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRolePOUsr role.
  
  Role Name: dbRolePOUsr
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRolePOUsr''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ActiveSystemClient','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRolePOUsr role.
  
  Role Name: dbRolePOUsr
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRolePOUsr''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ActiveSystemServer','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRolePOUsr role.
  
  Role Name: dbRolePOUsr
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRolePOUsr''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','Arizona','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRolePOUsr role.
  
  Role Name: dbRolePOUsr
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRolePOUsr''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ArizonaCASH','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRolePOUsr role.
  
  Role Name: dbRolePOUsr
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRolePOUsr''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ArizonaCUST','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRolePOUsr role.
  
  Role Name: dbRolePOUsr
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRolePOUsr''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','ArizonaLD','Pharmacies')
 
INSERT INTO #AllRoles(STR_Definition,STR_Database,STR_Product)VALUES('

/*=============================================================================

  Script to create dbRoleAppMgrUsr role.
  
  Role Name: dbRoleAppMgrUsr
  TEMPLATE: Default
  
  EXAMPLE OF SECURABLES TO SET: 
 
  INSERT INTO #Securables
  VALUES
  (''DB'',''GRANT'',''VIEW DEFINITION'','''',''''),
  (''SCHEMA'',''GRANT'',''SELECT,EXECUTE,INSERT,UPDATE,DELETE'','''',''AP''),
  (''TABLE'',''GRANT'',''INSERT,UPDATE'',''Address'',''dbo''),
  (''SP'',''GRANT'',''EXECUTE'',''sp_bmc_GetNextID'',''dbo''),
  (''ROLE'',''GRANT'',''db_datareader'','''','''')

  -----------------------------------------------
   
Generate date : 	2023-05-12 / up208700
	
=============================================================================*/

DECLARE @Command         nvarchar(max),
        @RoleName        varchar(60),
        @Users           varchar(255),
        @typeofobject    varchar(50),
        @grantordeny     varchar(10),
        @rightsaction    varchar(255),
        @objectname      varchar(255),
        @schemaid        varchar(10),
        @sysTarget       varchar(255),
        @sysType         varchar(255)

SET @RoleName = ''dbRoleAppMgrUsr''
SET @Command = ''''

/* TEMP TABLES */
CREATE TABLE #UsersOnRole(username varchar(255))
CREATE TABLE #Securables(typeofobject varchar(50), grantordeny varchar(10), rightsaction varchar(255), objectname varchar(255), schemaid varchar(10),N2 bit)

/* !!! LIST OF SECURABLES TO CHANGE !!! */

INSERT INTO #Securables
VALUES
(''ROLE'',''GRANT'',''DB_DATAREADER'','''',''dbo'',0)


/* GET ALL USERS ON THIS ROLE */
INSERT INTO #UsersOnRole
SELECT 
	members.name
FROM sys.database_role_members 
    JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id
    JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id
WHERE roles.name = @RoleName

/* CREATE ROLE */
SELECT @Command = ''
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '''''' + @RoleName + '''''' AND type = ''''R'''')
BEGIN
  CREATE ROLE ['' + @RoleName + ''] AUTHORIZATION [dbo]
  PRINT ''''CREATE ROLE ['' + @RoleName + '']''''
END
''
EXEC sp_executesql @Command

SET @Command = ''
DECLARE @SP_Name varchar(255)

''

/* SET ALL ROLE SECURABLES */
DECLARE SecurablesCurs CURSOR FOR 
SELECT typeofobject, grantordeny, rightsaction, objectname, schemaid
FROM #Securables
WHERE N2 = 0

OPEN SecurablesCurs
FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
WHILE @@FETCH_STATUS = 0
BEGIN

  IF @typeofobject = ''DB''
  BEGIN
    IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''DATABASE'') WHERE permission_name = '''' + @rightsaction + '''')
	BEGIN
      SET @Command = @Command + @grantordeny + '' '' + @rightsaction + '' TO ['' + @RoleName + '']
''
    END
   END

  IF @typeofobject = ''SCHEMA''
  BEGIN
  SET @Command = @Command + ''
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = '''''' + @schemaid + '''''') 
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''SCHEMA'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON SCHEMA::'' + @schemaid + '' TO ['' + @RoleName + '']
  END
END

''
  END

  IF @typeofobject in(''TABLE'',''SP'',''FUNCTIONS'',''VIEWS'')
  BEGIN

  IF @objectname like ''%[%]%''
  BEGIN

    IF @typeofobject = ''TABLE''
      BEGIN
        SET @sysTarget = ''sys.tables''
        SET @sysType = ''''
      END

      IF @typeofobject = ''SP''
      BEGIN
        SET @sysTarget = ''sys.procedures''
        SET @sysType = ''''
      END

      IF @typeofobject = ''FUNCTIONS''
      BEGIN
        SET @sysTarget = ''sys.objects''
        SET @sysType = '' and p.Type IN ( N''''FN'''', N''''IF'''', N''''TF'''', N''''FS'''', N''''FT'''' )''
      END

      IF @typeofobject = ''VIEWS''
      BEGIN
        SET @sysTarget = ''sys.views''
        SET @sysType = ''''
      END

    SET @Command = @Command + ''
DECLARE SP_cursor CURSOR FOR 
SELECT p.name FROM '' + @sysTarget + '' p JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE (p.name like '''''' + @objectname + '''''') and s.name = '''''' + @schemaid + '''' + @sysType + ''''''

OPEN SP_cursor
FETCH NEXT FROM SP_cursor INTO @SP_Name
WHILE @@FETCH_STATUS = 0
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    EXEC('''''' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['''' + @SP_Name + ''''] TO ['' + @RoleName + '']'''')
  END
  FETCH NEXT FROM SP_cursor INTO @SP_Name
END

CLOSE SP_cursor
DEALLOCATE SP_cursor

''

  END
  ELSE
  BEGIN

    SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.objects o WITH (NOLOCK) JOIN sys.schemas s ON s.schema_id = o.schema_id WHERE o.name = '''''' + @objectname + '''''' AND o.type IN (N''''U'''',''''P'''',''''V'''',''''FN'''',''''IF'''',''''TF'''') AND s.name = '''''' + @schemaid + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''OBJECT'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + '' ON ['' + @schemaid + ''].['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
  END
END

IF @typeofobject = ''ASSEMBLIES''
BEGIN
  SET @Command = @Command + ''
IF EXISTS(SELECT 1 FROM sys.assemblies WHERE NAME = '''''' + @objectname + '''''')
BEGIN
  IF EXISTS(SELECT 1 FROM sys.fn_builtin_permissions(''''ASSEMBLY'''') WHERE permission_name = '''''' + @rightsaction + '''''')
  BEGIN
    '' + @grantordeny + '' '' + @rightsaction + ''::['' + @objectname + ''] TO ['' + @RoleName + '']
  END
END

''
END

IF @typeofobject = ''ROLE''
BEGIN
  SET @Command = @Command + ''
IF NOT EXISTS (SELECT 1 FROM sys.database_role_members JOIN sys.database_principals roles ON database_role_members.role_principal_id = roles.principal_id JOIN sys.database_principals members ON database_role_members.member_principal_id = members.principal_id WHERE roles.name = '''''' + @rightsaction + '''''' AND members.name = '''''' + @RoleName + '''''')
BEGIN
  EXEC sp_addrolemember N'''''' + @rightsaction + '''''', N'''''' + @RoleName + ''''''
END

''
END

FETCH NEXT FROM SecurablesCurs INTO @typeofobject, @grantordeny, @rightsaction, @objectname, @schemaid
END

CLOSE SecurablesCurs
DEALLOCATE SecurablesCurs

PRINT ''SET ALL SECURABLES ON ROLE ['' + @RoleName + '']''
EXEC sp_executesql @Command

/* ADD USER */
DECLARE UsersCurs CURSOR FOR 
SELECT username 
  FROM #UsersOnRole

OPEN UsersCurs

FETCH NEXT FROM UsersCurs INTO @Users
WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @Command = ''
EXEC sp_addrolemember N'''''' + @RoleName + '''''', N'''''' + @Users + ''''''
PRINT ''''ADD USER ['' + @Users + ''] ON ROLE ['' + @RoleName + '']''''
''

FETCH NEXT FROM UsersCurs INTO @Users
END

CLOSE UsersCurs
DEALLOCATE UsersCurs

EXEC sp_executesql @Command


/*============================================================================= 
  Drop temp tables
=============================================================================*/ 
DROP TABLE #Securables
DROP TABLE #UsersOnRole
','Arizona','Pharmacies')
 

/*============================================================================= 
  Script to create / map all users and execute every roles on databases
=============================================================================*/ 

DECLARE @Command   nvarchar(max),
        @RoleName  varchar(60),
		@username  varchar(255),
        @Database VARCHAR(255)

SET @rolename = ''
SET @username = ''
SET @Command = ''
SET @Database = ''

CREATE TABLE #AllUsersAndRoles(databasename varchar(255), rolename varchar(255), username varchar(255))

INSERT INTO #AllUsersAndRoles
VALUES
('ActivePos_read','dbRoleActivePharmacy','sqlAppAPHUsr'),
('ActivePos_read','dbRoleCsltUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_Applications_Services'),
('ActivePos_read','dbRoleCsltUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Workstations_Applications_Services'),
('ActivePos_read','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_Applications_Services'),
('ActivePos_read','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Workstations_Applications_Services'),
('ActivePos_read','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_Applications_Services'),
('ActivePos_read','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Workstations_Applications_Services'),
('ActivePos_read','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_Applications_Services'),
('ActivePos_read','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Workstations_Applications_Services'),
('ActivePos_read','dbRoleCsltUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_Applications_Services'),
('ActivePos_read','dbRoleCsltUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Workstations_Applications_Services'),
('ActivePos_read','dbRoleCsltUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_Applications_Services'),
('ActivePos_read','dbRoleCsltUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Workstations_Applications_Services'),
('ActivePos_read','dbRoleDevUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_Development'),
('ActivePos_read','dbRoleDevUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Workstations_Development'),
('ActivePos_read','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_Development'),
('ActivePos_read','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Workstations_Development'),
('ActivePos_read','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_Development'),
('ActivePos_read','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Workstations_Development'),
('ActivePos_read','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_Development'),
('ActivePos_read','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Workstations_Development'),
('ActivePos_read','dbRoleDevUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_Development'),
('ActivePos_read','dbRoleDevUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Workstations_Development'),
('ActivePos_read','dbRoleDevUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_Development'),
('ActivePos_read','dbRoleDevUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Workstations_Development'),
('ActivePos_read','dbRoleIttechUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_IT_Field'),
('ActivePos_read','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_IT_Field'),
('ActivePos_read','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_IT_Field'),
('ActivePos_read','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_IT_Field'),
('ActivePos_read','dbRoleIttechUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_IT_Field'),
('ActivePos_read','dbRoleIttechUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_IT_Field'),
('ActivePos_read','dbRolePOUsr','AMAVITA\L-AM-AP-SQL-AMA_Pharmacy_Servers_Product_Owner'),
('ActivePos_read','dbRolePOUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_Product_Owner'),
('ActivePos_read','dbRolePOUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_Product_Owner'),
('ActivePos_read','dbRolePOUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_Product_Owner'),
('ActivePos_read','dbRolePOUsr','COOP-VITALITY\L-CV-AP-SQL-CVI_Pharmacy_Servers_Product_Owner'),
('ActivePos_read','dbRolePOUsr','SUNSTORE\L-SU-AP-SQL-SUN_Pharmacy_Servers_Product_Owner'),
('ActivePos_read','dbRoleQAtesters','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_QA_Testers'),
('ActivePos_read','dbRoleQAtesters','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_QA_Testers'),
('ActivePos_read','dbRoleQAtesters','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_QA_Testers'),
('ActivePos_read','dbRoleQAtesters','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_QA_Testers'),
('ActivePos_read','dbRoleQAtesters','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_QA_Testers'),
('ActivePos_read','dbRoleQAtesters','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_QA_Testers'),
('ActivePos_read','dbRoleSupUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_User_Support_Training'),
('ActivePos_read','dbRoleSupUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Workstations_User_Support_Training'),
('ActivePos_read','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_User_Support_Training'),
('ActivePos_read','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Workstations_User_Support_Training'),
('ActivePos_read','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_User_Support_Training'),
('ActivePos_read','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-cvi-Pharmacy_Workstations_User_Support_Training'),
('ActivePos_read','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_User_Support_Training'),
('ActivePos_read','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Workstations_User_Support_Training'),
('ActivePos_read','dbRoleSupUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_User_Support_Training'),
('ActivePos_read','dbRoleSupUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Workstations_User_Support_Training'),
('ActivePos_read','dbRoleSupUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_User_Support_Training'),
('ActivePos_read','dbRoleSupUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Workstations_User_Support_Training'),
('ActivePos_read','dbRoleTPPos','sqlLksrvTPPosusr'),
('ActivePos_server','dbRoleActiveConfig','ActiveConfig'),
('ActivePos_server','dbRoleActivePharmacy','sqlAppAPHUsr'),
('ActivePos_server','dbRoleCsltUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_Applications_Services'),
('ActivePos_server','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_Applications_Services'),
('ActivePos_server','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_Applications_Services'),
('ActivePos_server','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_Applications_Services'),
('ActivePos_server','dbRoleCsltUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_Applications_Services'),
('ActivePos_server','dbRoleCsltUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_Applications_Services'),
('ActivePos_server','dbRoleDevUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_Development'),
('ActivePos_server','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_Development'),
('ActivePos_server','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_Development'),
('ActivePos_server','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_Development'),
('ActivePos_server','dbRoleDevUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_Development'),
('ActivePos_server','dbRoleDevUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_Development'),
('ActivePos_server','dbRoleIttechUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_IT_Field'),
('ActivePos_server','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_IT_Field'),
('ActivePos_server','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_IT_Field'),
('ActivePos_server','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_IT_Field'),
('ActivePos_server','dbRoleIttechUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_IT_Field'),
('ActivePos_server','dbRoleIttechUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_IT_Field'),
('ActivePos_server','dbRolePOUsr','AMAVITA\L-AM-AP-SQL-AMA_Pharmacy_Servers_Product_Owner'),
('ActivePos_server','dbRolePOUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_Product_Owner'),
('ActivePos_server','dbRolePOUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_Product_Owner'),
('ActivePos_server','dbRolePOUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_Product_Owner'),
('ActivePos_server','dbRolePOUsr','COOP-VITALITY\L-CV-AP-SQL-CVI_Pharmacy_Servers_Product_Owner'),
('ActivePos_server','dbRolePOUsr','SUNSTORE\L-SU-AP-SQL-SUN_Pharmacy_Servers_Product_Owner'),
('ActivePos_server','dbRoleQAtesters','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_QA_Testers'),
('ActivePos_server','dbRoleQAtesters','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_QA_Testers'),
('ActivePos_server','dbRoleQAtesters','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_QA_Testers'),
('ActivePos_server','dbRoleQAtesters','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_QA_Testers'),
('ActivePos_server','dbRoleQAtesters','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_QA_Testers'),
('ActivePos_server','dbRoleQAtesters','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_QA_Testers'),
('ActivePos_server','dbRoleSupUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_User_Support_Training'),
('ActivePos_server','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_User_Support_Training'),
('ActivePos_server','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_User_Support_Training'),
('ActivePos_server','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_User_Support_Training'),
('ActivePos_server','dbRoleSupUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_User_Support_Training'),
('ActivePos_server','dbRoleSupUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_User_Support_Training'),
('ActivePos_server','dbRoleTPPos','sqlLksrvTPPosusr'),
('ActivePos_write','dbRoleActiveConfig','ActiveConfig'),
('ActivePos_write','dbRoleActivePharmacy','sqlAppAPHUsr'),
('ActivePos_write','dbRoleCsltUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_Applications_Services'),
('ActivePos_write','dbRoleCsltUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Workstations_Applications_Services'),
('ActivePos_write','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_Applications_Services'),
('ActivePos_write','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Workstations_Applications_Services'),
('ActivePos_write','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_Applications_Services'),
('ActivePos_write','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Workstations_Applications_Services'),
('ActivePos_write','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_Applications_Services'),
('ActivePos_write','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Workstations_Applications_Services'),
('ActivePos_write','dbRoleCsltUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_Applications_Services'),
('ActivePos_write','dbRoleCsltUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Workstations_Applications_Services'),
('ActivePos_write','dbRoleCsltUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_Applications_Services'),
('ActivePos_write','dbRoleCsltUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Workstations_Applications_Services'),
('ActivePos_write','dbRoleDevUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_Development'),
('ActivePos_write','dbRoleDevUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Workstations_Development'),
('ActivePos_write','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_Development'),
('ActivePos_write','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Workstations_Development'),
('ActivePos_write','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_Development'),
('ActivePos_write','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Workstations_Development'),
('ActivePos_write','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_Development'),
('ActivePos_write','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Workstations_Development'),
('ActivePos_write','dbRoleDevUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_Development'),
('ActivePos_write','dbRoleDevUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Workstations_Development'),
('ActivePos_write','dbRoleDevUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_Development'),
('ActivePos_write','dbRoleDevUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Workstations_Development'),
('ActivePos_write','dbRoleIttechUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_IT_Field'),
('ActivePos_write','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_IT_Field'),
('ActivePos_write','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_IT_Field'),
('ActivePos_write','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_IT_Field'),
('ActivePos_write','dbRoleIttechUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_IT_Field'),
('ActivePos_write','dbRoleIttechUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_IT_Field'),
('ActivePos_write','dbRolePOUsr','AMAVITA\L-AM-AP-SQL-AMA_Pharmacy_Servers_Product_Owner'),
('ActivePos_write','dbRolePOUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_Product_Owner'),
('ActivePos_write','dbRolePOUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_Product_Owner'),
('ActivePos_write','dbRolePOUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_Product_Owner'),
('ActivePos_write','dbRolePOUsr','COOP-VITALITY\L-CV-AP-SQL-CVI_Pharmacy_Servers_Product_Owner'),
('ActivePos_write','dbRolePOUsr','SUNSTORE\L-SU-AP-SQL-SUN_Pharmacy_Servers_Product_Owner'),
('ActivePos_write','dbRoleQAtesters','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_QA_Testers'),
('ActivePos_write','dbRoleQAtesters','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_QA_Testers'),
('ActivePos_write','dbRoleQAtesters','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_QA_Testers'),
('ActivePos_write','dbRoleQAtesters','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_QA_Testers'),
('ActivePos_write','dbRoleQAtesters','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_QA_Testers'),
('ActivePos_write','dbRoleQAtesters','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_QA_Testers'),
('ActivePos_write','dbRoleSupUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_User_Support_Training'),
('ActivePos_write','dbRoleSupUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Workstations_User_Support_Training'),
('ActivePos_write','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_User_Support_Training'),
('ActivePos_write','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Workstations_User_Support_Training'),
('ActivePos_write','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_User_Support_Training'),
('ActivePos_write','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-cvi-Pharmacy_Workstations_User_Support_Training'),
('ActivePos_write','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_User_Support_Training'),
('ActivePos_write','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Workstations_User_Support_Training'),
('ActivePos_write','dbRoleSupUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_User_Support_Training'),
('ActivePos_write','dbRoleSupUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Workstations_User_Support_Training'),
('ActivePos_write','dbRoleSupUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_User_Support_Training'),
('ActivePos_write','dbRoleSupUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Workstations_User_Support_Training'),
('ActivePos_write','dbRoleTPPos','sqlLksrvTPPosusr'),
('ActiveSystemClient','dbRoleActiveConfig','ActiveConfig'),
('ActiveSystemClient','dbRoleActivePharmacy','sqlAppAPHUsr'),
('ActiveSystemClient','dbRoleCsltUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_Applications_Services'),
('ActiveSystemClient','dbRoleCsltUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Workstations_Applications_Services'),
('ActiveSystemClient','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_Applications_Services'),
('ActiveSystemClient','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Workstations_Applications_Services'),
('ActiveSystemClient','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Workstations_User_Support_Training'),
('ActiveSystemClient','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_Applications_Services'),
('ActiveSystemClient','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Workstations_Applications_Services'),
('ActiveSystemClient','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-cvi-Pharmacy_Workstations_User_Support_Training'),
('ActiveSystemClient','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_Applications_Services'),
('ActiveSystemClient','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Workstations_User_Support_Training'),
('ActiveSystemClient','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Workstations_Windows_Operations'),
('ActiveSystemClient','dbRoleCsltUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_Applications_Services'),
('ActiveSystemClient','dbRoleCsltUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Workstations_Applications_Services'),
('ActiveSystemClient','dbRoleCsltUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_Applications_Services'),
('ActiveSystemClient','dbRoleCsltUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Workstations_Applications_Services'),
('ActiveSystemClient','dbRoleDevUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_Development'),
('ActiveSystemClient','dbRoleDevUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Workstations_Development'),
('ActiveSystemClient','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_Development'),
('ActiveSystemClient','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Workstations_Development'),
('ActiveSystemClient','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_Development'),
('ActiveSystemClient','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Workstations_Development'),
('ActiveSystemClient','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-cvi-Pharmacy_Workstations_User_Support_Training'),
('ActiveSystemClient','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_Development'),
('ActiveSystemClient','dbRoleDevUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_Development'),
('ActiveSystemClient','dbRoleDevUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Workstations_Development'),
('ActiveSystemClient','dbRoleDevUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_Development'),
('ActiveSystemClient','dbRoleDevUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Workstations_Development'),
('ActiveSystemClient','dbRoleIttechUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_IT_Field'),
('ActiveSystemClient','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_IT_Field'),
('ActiveSystemClient','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_IT_Field'),
('ActiveSystemClient','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_IT_Field'),
('ActiveSystemClient','dbRoleIttechUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_IT_Field'),
('ActiveSystemClient','dbRoleIttechUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_IT_Field'),
('ActiveSystemClient','dbRolePOUsr','AMAVITA\L-AM-AP-SQL-AMA_Pharmacy_Servers_Product_Owner'),
('ActiveSystemClient','dbRolePOUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_Product_Owner'),
('ActiveSystemClient','dbRolePOUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_Product_Owner'),
('ActiveSystemClient','dbRolePOUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_Product_Owner'),
('ActiveSystemClient','dbRolePOUsr','COOP-VITALITY\L-CV-AP-SQL-CVI_Pharmacy_Servers_Product_Owner'),
('ActiveSystemClient','dbRolePOUsr','SUNSTORE\L-SU-AP-SQL-SUN_Pharmacy_Servers_Product_Owner'),
('ActiveSystemClient','dbRoleQAtesters','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_QA_Testers'),
('ActiveSystemClient','dbRoleQAtesters','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_QA_Testers'),
('ActiveSystemClient','dbRoleQAtesters','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_QA_Testers'),
('ActiveSystemClient','dbRoleQAtesters','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_QA_Testers'),
('ActiveSystemClient','dbRoleQAtesters','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_QA_Testers'),
('ActiveSystemClient','dbRoleQAtesters','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_QA_Testers'),
('ActiveSystemClient','dbRoleSupUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_User_Support_Training'),
('ActiveSystemClient','dbRoleSupUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Workstations_User_Support_Training'),
('ActiveSystemClient','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_User_Support_Training'),
('ActiveSystemClient','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Workstations_User_Support_Training'),
('ActiveSystemClient','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_User_Support_Training'),
('ActiveSystemClient','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-cvi-Pharmacy_Workstations_User_Support_Training'),
('ActiveSystemClient','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_User_Support_Training'),
('ActiveSystemClient','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Workstations_User_Support_Training'),
('ActiveSystemClient','dbRoleSupUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_User_Support_Training'),
('ActiveSystemClient','dbRoleSupUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Workstations_User_Support_Training'),
('ActiveSystemClient','dbRoleSupUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_User_Support_Training'),
('ActiveSystemClient','dbRoleSupUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Workstations_User_Support_Training'),
('ActiveSystemServer','dbRoleActiveConfig','ActiveConfig'),
('ActiveSystemServer','dbRoleActivePharmacy','sqlAppAPHUsr'),
('ActiveSystemServer','dbRoleCsltUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_Applications_Services'),
('ActiveSystemServer','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_Applications_Services'),
('ActiveSystemServer','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_Applications_Services'),
('ActiveSystemServer','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_Applications_Services'),
('ActiveSystemServer','dbRoleCsltUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_Applications_Services'),
('ActiveSystemServer','dbRoleCsltUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_Applications_Services'),
('ActiveSystemServer','dbRoleDevUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_Development'),
('ActiveSystemServer','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_Development'),
('ActiveSystemServer','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_Development'),
('ActiveSystemServer','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_Development'),
('ActiveSystemServer','dbRoleDevUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_Development'),
('ActiveSystemServer','dbRoleDevUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_Development'),
('ActiveSystemServer','dbRoleIttechUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_IT_Field'),
('ActiveSystemServer','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_IT_Field'),
('ActiveSystemServer','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_IT_Field'),
('ActiveSystemServer','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_IT_Field'),
('ActiveSystemServer','dbRoleIttechUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_IT_Field'),
('ActiveSystemServer','dbRoleIttechUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_IT_Field'),
('ActiveSystemServer','dbRolePOUsr','AMAVITA\L-AM-AP-SQL-AMA_Pharmacy_Servers_Product_Owner'),
('ActiveSystemServer','dbRolePOUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_Product_Owner'),
('ActiveSystemServer','dbRolePOUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_Product_Owner'),
('ActiveSystemServer','dbRolePOUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_Product_Owner'),
('ActiveSystemServer','dbRolePOUsr','COOP-VITALITY\L-CV-AP-SQL-CVI_Pharmacy_Servers_Product_Owner'),
('ActiveSystemServer','dbRolePOUsr','SUNSTORE\L-SU-AP-SQL-SUN_Pharmacy_Servers_Product_Owner'),
('ActiveSystemServer','dbRoleQAtesters','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_QA_Testers'),
('ActiveSystemServer','dbRoleQAtesters','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_QA_Testers'),
('ActiveSystemServer','dbRoleQAtesters','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_QA_Testers'),
('ActiveSystemServer','dbRoleQAtesters','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_QA_Testers'),
('ActiveSystemServer','dbRoleQAtesters','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_QA_Testers'),
('ActiveSystemServer','dbRoleQAtesters','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_QA_Testers'),
('ActiveSystemServer','dbRoleSupUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_User_Support_Training'),
('ActiveSystemServer','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_User_Support_Training'),
('ActiveSystemServer','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_User_Support_Training'),
('ActiveSystemServer','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_User_Support_Training'),
('ActiveSystemServer','dbRoleSupUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_User_Support_Training'),
('ActiveSystemServer','dbRoleSupUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_User_Support_Training'),
('ActiveSystemServer','dbRoleTPPos','sqlLksrvTPPosusr'),
('Arizona','dbRoleActivePharmacy','sqlAppAPHUsr'),
('Arizona','dbRoleAppMgrUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_Application_Manager'),
('Arizona','dbRoleAppMgrUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_Application_Manager'),
('Arizona','dbRoleAppMgrUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_Application_Manager'),
('Arizona','dbRoleAppMgrUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_Application_Manager'),
('Arizona','dbRoleAppMgrUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_Application_Manager'),
('Arizona','dbRoleAppMgrUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_Application_Manager'),
('Arizona','dbRoleArizonaCASH','arizonacash'),
('Arizona','dbRoleAtlas','AMAVITA\L-AM-AP-SQL-Atlas-W'),
('Arizona','dbRoleAtlas','AMAVITA\L-AM-AP-SQL-Atlas_Dev-W'),
('Arizona','dbRoleAtlas','CENTRALINFRA\L-CI-AP-SQL-Atlas-W'),
('Arizona','dbRoleAtlas','CENTRALINFRA\L-CI-AP-SQL-Atlas_Dev-W'),
('Arizona','dbRoleAtlas','COOP-VITALITY\L-CV-AP-SQL-Atlas-W'),
('Arizona','dbRoleAtlas','COOP-VITALITY\L-CV-AP-SQL-Atlas_Dev-W'),
('Arizona','dbRoleAtlas','SUNSTORE\L-SU-AP-SQL-Atlas-W'),
('Arizona','dbRoleAtlas','SUNSTORE\L-SU-AP-SQL-Atlas_Dev-W'),
('Arizona','dbRoleCsltUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_Applications_Services'),
('Arizona','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_Applications_Services'),
('Arizona','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_Applications_Services'),
('Arizona','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_Applications_Services'),
('Arizona','dbRoleCsltUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_Applications_Services'),
('Arizona','dbRoleCsltUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_Applications_Services'),
('Arizona','dbRoleDataMonitoring','datamonitoring'),
('Arizona','dbRoleDevUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_Development'),
('Arizona','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_Development'),
('Arizona','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_Development'),
('Arizona','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_Development'),
('Arizona','dbRoleDevUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_Development'),
('Arizona','dbRoleDevUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_Development'),
('Arizona','dbRoleGaia','sqlAppGaiaUsr'),
('Arizona','dbRoleGcStock','gcstock'),
('Arizona','dbRoleGroupRepetition','sqlSyncDmUsr'),
('Arizona','dbRoleIttechUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_IT_Field'),
('Arizona','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_IT_Field'),
('Arizona','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_IT_Field'),
('Arizona','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_IT_Field'),
('Arizona','dbRoleIttechUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_IT_Field'),
('Arizona','dbRoleIttechUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_IT_Field'),
('Arizona','dbRolePOUsr','AMAVITA\L-AM-AP-SQL-AMA_Pharmacy_Servers_Product_Owner'),
('Arizona','dbRolePOUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_Product_Owner'),
('Arizona','dbRolePOUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_Product_Owner'),
('Arizona','dbRolePOUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_Product_Owner'),
('Arizona','dbRolePOUsr','COOP-VITALITY\L-CV-AP-SQL-CVI_Pharmacy_Servers_Product_Owner'),
('Arizona','dbRolePOUsr','SUNSTORE\L-SU-AP-SQL-SUN_Pharmacy_Servers_Product_Owner'),
('Arizona','dbRoleQAtesters','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_QA_Testers'),
('Arizona','dbRoleQAtesters','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_QA_Testers'),
('Arizona','dbRoleQAtesters','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_QA_Testers'),
('Arizona','dbRoleQAtesters','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_QA_Testers'),
('Arizona','dbRoleQAtesters','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_QA_Testers'),
('Arizona','dbRoleQAtesters','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_QA_Testers'),
('Arizona','dbRoleSupUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_User_Support_Training'),
('Arizona','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_User_Support_Training'),
('Arizona','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_User_Support_Training'),
('Arizona','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_User_Support_Training'),
('Arizona','dbRoleSupUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_User_Support_Training'),
('Arizona','dbRoleSupUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_User_Support_Training'),
('Arizona','dbRoleSyncAccountingExtraction','sqlSyncAccountingExtractionUsr'),
('Arizona','dbRoleTPPos','sqlLksrvTPPosusr'),
('Arizona','dbRoleTPSSIS','sqlSSISTPUsr'),
('Arizona','dbRoleTriapharmChangeTracking','sqlSyncDmUsr'),
('Arizona','dbRoleTriapharmCounter','apscounter'),
('Arizona','dbRoleTriapharmUser','bmcarizona'),
('ArizonaCASH','dbRoleActivePharmacy','sqlAppAPHUsr'),
('ArizonaCASH','dbRoleArizonaCASH','arizonacash'),
('ArizonaCASH','dbRoleAtlas','AMAVITA\L-AM-AP-SQL-Atlas-W'),
('ArizonaCASH','dbRoleAtlas','AMAVITA\L-AM-AP-SQL-Atlas_Dev-W'),
('ArizonaCASH','dbRoleAtlas','CENTRALINFRA\L-CI-AP-SQL-Atlas-W'),
('ArizonaCASH','dbRoleAtlas','CENTRALINFRA\L-CI-AP-SQL-Atlas_Dev-W'),
('ArizonaCASH','dbRoleAtlas','COOP-VITALITY\L-CV-AP-SQL-Atlas-W'),
('ArizonaCASH','dbRoleAtlas','COOP-VITALITY\L-CV-AP-SQL-Atlas_Dev-W'),
('ArizonaCASH','dbRoleAtlas','SUNSTORE\L-SU-AP-SQL-Atlas-W'),
('ArizonaCASH','dbRoleAtlas','SUNSTORE\L-SU-AP-SQL-Atlas_Dev-W'),
('ArizonaCASH','dbRoleCsltUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_Applications_Services'),
('ArizonaCASH','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_Applications_Services'),
('ArizonaCASH','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_Applications_Services'),
('ArizonaCASH','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_Applications_Services'),
('ArizonaCASH','dbRoleCsltUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_Applications_Services'),
('ArizonaCASH','dbRoleCsltUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_Applications_Services'),
('ArizonaCASH','dbRoleDevUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_Development'),
('ArizonaCASH','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_Development'),
('ArizonaCASH','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_Development'),
('ArizonaCASH','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_Development'),
('ArizonaCASH','dbRoleDevUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_Development'),
('ArizonaCASH','dbRoleDevUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_Development'),
('ArizonaCASH','dbRoleIttechUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_IT_Field'),
('ArizonaCASH','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_IT_Field'),
('ArizonaCASH','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_IT_Field'),
('ArizonaCASH','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_IT_Field'),
('ArizonaCASH','dbRoleIttechUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_IT_Field'),
('ArizonaCASH','dbRoleIttechUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_IT_Field'),
('ArizonaCASH','dbRolePOUsr','AMAVITA\L-AM-AP-SQL-AMA_Pharmacy_Servers_Product_Owner'),
('ArizonaCASH','dbRolePOUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_Product_Owner'),
('ArizonaCASH','dbRolePOUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_Product_Owner'),
('ArizonaCASH','dbRolePOUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_Product_Owner'),
('ArizonaCASH','dbRolePOUsr','COOP-VITALITY\L-CV-AP-SQL-CVI_Pharmacy_Servers_Product_Owner'),
('ArizonaCASH','dbRolePOUsr','SUNSTORE\L-SU-AP-SQL-SUN_Pharmacy_Servers_Product_Owner'),
('ArizonaCASH','dbRoleQAtesters','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_QA_Testers'),
('ArizonaCASH','dbRoleQAtesters','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_QA_Testers'),
('ArizonaCASH','dbRoleQAtesters','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_QA_Testers'),
('ArizonaCASH','dbRoleQAtesters','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_QA_Testers'),
('ArizonaCASH','dbRoleQAtesters','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_QA_Testers'),
('ArizonaCASH','dbRoleQAtesters','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_QA_Testers'),
('ArizonaCASH','dbRoleSupUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_User_Support_Training'),
('ArizonaCASH','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_User_Support_Training'),
('ArizonaCASH','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_User_Support_Training'),
('ArizonaCASH','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_User_Support_Training'),
('ArizonaCASH','dbRoleSupUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_User_Support_Training'),
('ArizonaCASH','dbRoleSupUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_User_Support_Training'),
('ArizonaCASH','dbRoleSyncAccountingExtraction','sqlSyncAccountingExtractionUsr'),
('ArizonaCASH','dbRoleTPPos','sqlLksrvTPPosusr'),
('ArizonaCASH','dbRoleTriapharmUser','bmcarizona'),
('ArizonaCUST','dbRoleCsltUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_Applications_Services'),
('ArizonaCUST','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_Applications_Services'),
('ArizonaCUST','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_Applications_Services'),
('ArizonaCUST','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_Applications_Services'),
('ArizonaCUST','dbRoleCsltUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_Applications_Services'),
('ArizonaCUST','dbRoleCsltUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_Applications_Services'),
('ArizonaCUST','dbRoleDevUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_Development'),
('ArizonaCUST','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_Development'),
('ArizonaCUST','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_Development'),
('ArizonaCUST','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_Development'),
('ArizonaCUST','dbRoleDevUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_Development'),
('ArizonaCUST','dbRoleDevUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_Development'),
('ArizonaCUST','dbRoleIttechUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_IT_Field'),
('ArizonaCUST','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_IT_Field'),
('ArizonaCUST','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_IT_Field'),
('ArizonaCUST','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_IT_Field'),
('ArizonaCUST','dbRoleIttechUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_IT_Field'),
('ArizonaCUST','dbRoleIttechUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_IT_Field'),
('ArizonaCUST','dbRolePOUsr','AMAVITA\L-AM-AP-SQL-AMA_Pharmacy_Servers_Product_Owner'),
('ArizonaCUST','dbRolePOUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_Product_Owner'),
('ArizonaCUST','dbRolePOUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_Product_Owner'),
('ArizonaCUST','dbRolePOUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_Product_Owner'),
('ArizonaCUST','dbRolePOUsr','COOP-VITALITY\L-CV-AP-SQL-CVI_Pharmacy_Servers_Product_Owner'),
('ArizonaCUST','dbRolePOUsr','SUNSTORE\L-SU-AP-SQL-SUN_Pharmacy_Servers_Product_Owner'),
('ArizonaCUST','dbRoleQAtesters','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_QA_Testers'),
('ArizonaCUST','dbRoleQAtesters','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_QA_Testers'),
('ArizonaCUST','dbRoleQAtesters','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_QA_Testers'),
('ArizonaCUST','dbRoleQAtesters','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_QA_Testers'),
('ArizonaCUST','dbRoleQAtesters','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_QA_Testers'),
('ArizonaCUST','dbRoleQAtesters','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_QA_Testers'),
('ArizonaCUST','dbRoleSupUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_User_Support_Training'),
('ArizonaCUST','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_User_Support_Training'),
('ArizonaCUST','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_User_Support_Training'),
('ArizonaCUST','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_User_Support_Training'),
('ArizonaCUST','dbRoleSupUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_User_Support_Training'),
('ArizonaCUST','dbRoleSupUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_User_Support_Training'),
('ArizonaCUST','dbRoleSyncAccountingExtraction','sqlSyncAccountingExtractionUsr'),
('ArizonaLD','dbRoleCsltUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_Applications_Services'),
('ArizonaLD','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_Applications_Services'),
('ArizonaLD','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_Applications_Services'),
('ArizonaLD','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_Applications_Services'),
('ArizonaLD','dbRoleCsltUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_Applications_Services'),
('ArizonaLD','dbRoleCsltUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_Applications_Services'),
('ArizonaLD','dbRoleDevUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_Development'),
('ArizonaLD','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_Development'),
('ArizonaLD','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_Development'),
('ArizonaLD','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_Development'),
('ArizonaLD','dbRoleDevUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_Development'),
('ArizonaLD','dbRoleDevUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_Development'),
('ArizonaLD','dbRoleIttechUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_IT_Field'),
('ArizonaLD','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_IT_Field'),
('ArizonaLD','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_IT_Field'),
('ArizonaLD','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_IT_Field'),
('ArizonaLD','dbRoleIttechUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_IT_Field'),
('ArizonaLD','dbRoleIttechUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_IT_Field'),
('ArizonaLD','dbRolePOUsr','AMAVITA\L-AM-AP-SQL-AMA_Pharmacy_Servers_Product_Owner'),
('ArizonaLD','dbRolePOUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_Product_Owner'),
('ArizonaLD','dbRolePOUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_Product_Owner'),
('ArizonaLD','dbRolePOUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_Product_Owner'),
('ArizonaLD','dbRolePOUsr','COOP-VITALITY\L-CV-AP-SQL-CVI_Pharmacy_Servers_Product_Owner'),
('ArizonaLD','dbRolePOUsr','SUNSTORE\L-SU-AP-SQL-SUN_Pharmacy_Servers_Product_Owner'),
('ArizonaLD','dbRoleQAtesters','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_QA_Testers'),
('ArizonaLD','dbRoleQAtesters','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_QA_Testers'),
('ArizonaLD','dbRoleQAtesters','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_QA_Testers'),
('ArizonaLD','dbRoleQAtesters','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_QA_Testers'),
('ArizonaLD','dbRoleQAtesters','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_QA_Testers'),
('ArizonaLD','dbRoleQAtesters','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_QA_Testers'),
('ArizonaLD','dbRoleSupUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_User_Support_Training'),
('ArizonaLD','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_User_Support_Training'),
('ArizonaLD','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_User_Support_Training'),
('ArizonaLD','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_User_Support_Training'),
('ArizonaLD','dbRoleSupUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_User_Support_Training'),
('ArizonaLD','dbRoleSupUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_User_Support_Training'),
('ArizonaTest','dbRoleCsltUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_Applications_Services'),
('ArizonaTest','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_Applications_Services'),
('ArizonaTest','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_Applications_Services'),
('ArizonaTest','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_Applications_Services'),
('ArizonaTest','dbRoleCsltUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_Applications_Services'),
('ArizonaTest','dbRoleCsltUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_Applications_Services'),
('ArizonaTest','dbRoleDevUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_Development'),
('ArizonaTest','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_Development'),
('ArizonaTest','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_Development'),
('ArizonaTest','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_Development'),
('ArizonaTest','dbRoleDevUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_Development'),
('ArizonaTest','dbRoleDevUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_Development'),
('ArizonaTest','dbRoleIttechUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_IT_Field'),
('ArizonaTest','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_IT_Field'),
('ArizonaTest','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_IT_Field'),
('ArizonaTest','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_IT_Field'),
('ArizonaTest','dbRoleIttechUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_IT_Field'),
('ArizonaTest','dbRoleIttechUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_IT_Field'),
('ArizonaTest','dbRoleSupUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_User_Support_Training'),
('ArizonaTest','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_User_Support_Training'),
('ArizonaTest','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_User_Support_Training'),
('ArizonaTest','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_User_Support_Training'),
('ArizonaTest','dbRoleSupUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_User_Support_Training'),
('ArizonaTest','dbRoleSupUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_User_Support_Training'),
('distribution','dbRoleCsltUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_Applications_Services'),
('distribution','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_Applications_Services'),
('distribution','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_Applications_Services'),
('distribution','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-GCA-PharmINDEX_Applications_Services'),
('distribution','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-GCA-TriaFACT_Applications_Services'),
('distribution','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_Applications_Services'),
('distribution','dbRoleCsltUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_Applications_Services'),
('distribution','dbRoleCsltUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_Applications_Services'),
('distribution','dbRoleDevUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_Development'),
('distribution','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_Development'),
('distribution','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_Development'),
('distribution','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-GCA-PharmINDEX_Development'),
('distribution','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-GCA-TriaFACT_Development'),
('distribution','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_Development'),
('distribution','dbRoleDevUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_Development'),
('distribution','dbRoleDevUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_Development'),
('distribution','dbRoleIttechUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_IT_Field'),
('distribution','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_IT_Field'),
('distribution','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_IT_Field'),
('distribution','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_IT_Field'),
('distribution','dbRoleIttechUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_IT_Field'),
('distribution','dbRoleIttechUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_IT_Field'),
('distribution','dbRoleSupUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_User_Support_Training'),
('distribution','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_User_Support_Training'),
('distribution','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_User_Support_Training'),
('distribution','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_User_Support_Training'),
('distribution','dbRoleSupUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_User_Support_Training'),
('distribution','dbRoleSupUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_User_Support_Training'),
('distribution','dbRoleTPPos','sqlLksrvTPPosusr'),
('Golabo','dbRoleDevUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_Development'),
('Golabo','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_Development'),
('Golabo','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_Development'),
('Golabo','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_Development'),
('Golabo','dbRoleDevUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_Development'),
('Golabo','dbRoleDevUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_Development'),
('HCITools','dbRoleCsltUsr','AAI\L-AA-AP-SQL-AAI-Datamart_Applications_Services'),
('HCITools','dbRoleCsltUsr','AMAVITA\L-AM-AP-SQL-AMA-Address_Repository_Applications_Services'),
('HCITools','dbRoleCsltUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_Applications_Services'),
('HCITools','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_Applications_Services'),
('HCITools','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_Applications_Services'),
('HCITools','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-GCA-Atlas_Applications_Services'),
('HCITools','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-GCA-Datamart_Applications_Services'),
('HCITools','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-GCA-Gaia_Applications_Services'),
('HCITools','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-GCA-PharmINDEX_Applications_Services'),
('HCITools','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-GCA-Pricing_Applications_Services'),
('HCITools','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-GCA-TriaFACT_Applications_Services'),
('HCITools','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-GCA-triaSCAN_Applications_Services'),
('HCITools','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-GCM-J2I_Database_Administrator'),
('HCITools','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_Applications_Services'),
('HCITools','dbRoleCsltUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Address_Repository_Applications_Services'),
('HCITools','dbRoleCsltUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_Applications_Services'),
('HCITools','dbRoleCsltUsr','SUNSTORE\L-SU-AP-SQL-SUN-Address_Repository_Applications_Services'),
('HCITools','dbRoleCsltUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_Applications_Services'),
('HCITools','dbRoleDataMonitoring','datamonitoring'),
('HCITools','dbRoleDevUsr','AAI\L-AA-AP-SQL-AAI-Datamart_Development'),
('HCITools','dbRoleDevUsr','AMAVITA\L-AM-AP-SQL-AMA-Address_Repository_Development'),
('HCITools','dbRoleDevUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_Development'),
('HCITools','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_Development'),
('HCITools','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_Development'),
('HCITools','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-GCA-Atlas_Development'),
('HCITools','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-GCA-Datamart_Development'),
('HCITools','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-GCA-Gaia_Development'),
('HCITools','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-GCA-Monitoring_Development'),
('HCITools','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-GCA-PharmINDEX_Development'),
('HCITools','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-GCA-Pricing_Development'),
('HCITools','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-GCA-TriaFACT_Development'),
('HCITools','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-GCA-triaSCAN_Development'),
('HCITools','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-GCM-J2I_Development'),
('HCITools','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_Development'),
('HCITools','dbRoleDevUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Address_Repository_Development'),
('HCITools','dbRoleDevUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_Development'),
('HCITools','dbRoleDevUsr','SUNSTORE\L-SU-AP-SQL-SUN-Address_Repository_Development'),
('HCITools','dbRoleDevUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_Development'),
('HCITools','dbRoleIttechUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_IT_Field'),
('HCITools','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_IT_Field'),
('HCITools','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_IT_Field'),
('HCITools','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_IT_Field'),
('HCITools','dbRoleIttechUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_IT_Field'),
('HCITools','dbRoleIttechUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_IT_Field'),
('HCITools','dbRoleNagiosMonitoring','sqlMonNagiosUsr'),
('HCITools','dbRoleSSRSMonitoring','sqlMonSSRSUsr'),
('HCITools','dbRoleSupUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_User_Support_Training'),
('HCITools','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_User_Support_Training'),
('HCITools','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_User_Support_Training'),
('HCITools','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_User_Support_Training'),
('HCITools','dbRoleSupUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_User_Support_Training'),
('HCITools','dbRoleSupUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_User_Support_Training'),
('master','dbRoleAtlas','AMAVITA\L-AM-AP-SQL-Atlas-W'),
('master','dbRoleAtlas','AMAVITA\L-AM-AP-SQL-Atlas_Dev-W'),
('master','dbRoleAtlas','CENTRALINFRA\L-CI-AP-SQL-Atlas-W'),
('master','dbRoleAtlas','CENTRALINFRA\L-CI-AP-SQL-Atlas_Dev-W'),
('master','dbRoleAtlas','COOP-VITALITY\L-CV-AP-SQL-Atlas-W'),
('master','dbRoleAtlas','COOP-VITALITY\L-CV-AP-SQL-Atlas_Dev-W'),
('master','dbRoleAtlas','SUNSTORE\L-SU-AP-SQL-Atlas-W'),
('master','dbRoleAtlas','SUNSTORE\L-SU-AP-SQL-Atlas_Dev-W'),
('master','dbRoleSyncAccountingExtraction','sqlSyncAccountingExtractionUsr'),
('master','dbRoleTPPos','sqlLksrvTPPosusr'),
('msdb','dbRoleCsltUsr','AAI\L-AA-AP-SQL-AAI-Datamart_Applications_Services'),
('msdb','dbRoleCsltUsr','AMAVITA\L-AM-AP-SQL-AMA-Address_Repository_Applications_Services'),
('msdb','dbRoleCsltUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_Applications_Services'),
('msdb','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_Applications_Services'),
('msdb','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_Applications_Services'),
('msdb','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-GCA-Atlas_Applications_Services'),
('msdb','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-GCA-Datamart_Applications_Services'),
('msdb','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-GCA-Gaia_Applications_Services'),
('msdb','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-GCA-PharmINDEX_Applications_Services'),
('msdb','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-GCA-Pricing_Applications_Services'),
('msdb','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-GCA-TriaFACT_Applications_Services'),
('msdb','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-GCA-triaSCAN_Applications_Services'),
('msdb','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-GCM-J2I_Applications_Services'),
('msdb','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_Applications_Services'),
('msdb','dbRoleCsltUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Address_Repository_Applications_Services'),
('msdb','dbRoleCsltUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_Applications_Services'),
('msdb','dbRoleCsltUsr','SUNSTORE\L-SU-AP-SQL-SUN-Address_Repository_Applications_Services'),
('msdb','dbRoleCsltUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_Applications_Services'),
('msdb','dbRoleDataMonitoring','datamonitoring'),
('msdb','dbRoleDevUsr','AAI\L-AA-AP-SQL-AAI-Datamart_Development'),
('msdb','dbRoleDevUsr','AMAVITA\L-AM-AP-SQL-AMA-Address_Repository_Development'),
('msdb','dbRoleDevUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_Development'),
('msdb','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_Development'),
('msdb','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_Development'),
('msdb','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-GCA-Atlas_Development'),
('msdb','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-GCA-Datamart_Development'),
('msdb','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-GCA-Monitoring_Development'),
('msdb','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-GCA-PharmINDEX_Development'),
('msdb','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-GCA-Pricing_Development'),
('msdb','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-GCA-TriaFACT_Development'),
('msdb','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-GCA-triaSCAN_Development'),
('msdb','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-GCM-J2I_Development'),
('msdb','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_Development'),
('msdb','dbRoleDevUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Address_Repository_Development'),
('msdb','dbRoleDevUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_Development'),
('msdb','dbRoleDevUsr','SUNSTORE\L-SU-AP-SQL-SUN-Address_Repository_Development'),
('msdb','dbRoleDevUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_Development'),
('msdb','dbRoleIttechUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_IT_Field'),
('msdb','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_IT_Field'),
('msdb','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_IT_Field'),
('msdb','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_IT_Field'),
('msdb','dbRoleIttechUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_IT_Field'),
('msdb','dbRoleIttechUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_IT_Field'),
('msdb','dbRoleSupUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_User_Support_Training'),
('msdb','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_User_Support_Training'),
('msdb','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_User_Support_Training'),
('msdb','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_User_Support_Training'),
('msdb','dbRoleSupUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_User_Support_Training'),
('msdb','dbRoleSupUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_User_Support_Training'),
('msdb','dbRoleTPPos','sqlLksrvTPPosusr'),
('Symbiose','dbRoleCsltUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_Applications_Services'),
('Symbiose','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_Applications_Services'),
('Symbiose','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_Applications_Services'),
('Symbiose','dbRoleCsltUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_Applications_Services'),
('Symbiose','dbRoleCsltUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_Applications_Services'),
('Symbiose','dbRoleCsltUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_Applications_Services'),
('Symbiose','dbRoleDevUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_Development'),
('Symbiose','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_Development'),
('Symbiose','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_Development'),
('Symbiose','dbRoleDevUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_Development'),
('Symbiose','dbRoleDevUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_Development'),
('Symbiose','dbRoleDevUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_Development'),
('Symbiose','dbRoleIttechUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_IT_Field'),
('Symbiose','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_IT_Field'),
('Symbiose','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_IT_Field'),
('Symbiose','dbRoleIttechUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_IT_Field'),
('Symbiose','dbRoleIttechUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_IT_Field'),
('Symbiose','dbRoleIttechUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_IT_Field'),
('Symbiose','dbRoleSupUsr','AMAVITA\L-AM-AP-SQL-AMA-Pharmacy_Servers_User_Support_Training'),
('Symbiose','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-AMA-Pharmacy_Servers_User_Support_Training'),
('Symbiose','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-CVI-Pharmacy_Servers_User_Support_Training'),
('Symbiose','dbRoleSupUsr','CENTRALINFRA\L-CI-AP-SQL-SUN-Pharmacy_Servers_User_Support_Training'),
('Symbiose','dbRoleSupUsr','COOP-VITALITY\L-CV-AP-SQL-CVI-Pharmacy_Servers_User_Support_Training'),
('Symbiose','dbRoleSupUsr','SUNSTORE\L-SU-AP-SQL-SUN-Pharmacy_Servers_User_Support_Training')

DECLARE AllDb CURSOR FOR SELECT DISTINCT STR_Database FROM #AllRoles STR JOIN master.sys.databases D ON D.name = STR.STR_Database
OPEN AllDb

FETCH NEXT FROM AllDb INTO @Database
WHILE @@FETCH_STATUS = 0
BEGIN
   
  SELECT @Command = 'USE ' + @Database + '

DECLARE @Roles nvarchar(max)

  DECLARE AllRoles CURSOR FOR SELECT STR_Definition FROM #AllRoles WHERE STR_Database = ''' + @Database + '''
  OPEN AllRoles

  FETCH NEXT FROM AllRoles INTO @Roles
  WHILE @@FETCH_STATUS = 0
  BEGIN
    EXEC sp_executesql @Roles
  FETCH NEXT FROM AllRoles INTO @Roles
  END

CLOSE AllRoles
DEALLOCATE AllRoles
'

EXEC sp_executesql @Command

FETCH NEXT FROM AllDb INTO @Database
END

CLOSE AllDb
DEALLOCATE AllDb

DECLARE MapUsersAndRolesCurs CURSOR FOR 
SELECT databasename, rolename, username FROM #AllUsersAndRoles AUAR JOIN master.sys.databases D ON D.name = AUAR.databasename

OPEN MapUsersAndRolesCurs
FETCH NEXT FROM MapUsersAndRolesCurs INTO @Database, @rolename, @username
WHILE @@FETCH_STATUS = 0
BEGIN
       
  SET @Command = 'USE ' + @Database + '
IF EXISTS (SELECT 1 FROM master.dbo.syslogins WHERE name = ''' + @username + ''')
BEGIN
  IF EXISTS (SELECT 1 FROM sys.database_principals WHERE name = N''' + @rolename + ''' AND [type] = ''R'')
  BEGIN
    IF EXISTS (SELECT 1 FROM sys.database_principals WHERE name = N''' + @username + ''')
    BEGIN
      ALTER USER [' + @username + '] WITH LOGIN = [' + @username + ']
      EXEC sp_addrolemember N''' + @rolename + ''', N''' + @username + '''
    END
    ELSE
    BEGIN
      CREATE USER [' + @username + '] FOR LOGIN [' + @username + '] WITH DEFAULT_SCHEMA=[dbo]
      EXEC sp_addrolemember N''' + @rolename + ''', N''' + @username + '''
    END
  END
END
'

EXEC sp_executesql @Command

FETCH NEXT FROM MapUsersAndRolesCurs INTO @Database, @rolename, @username
END
     
CLOSE MapUsersAndRolesCurs
DEALLOCATE MapUsersAndRolesCurs

DROP TABLE #AllUsersAndRoles
DROP TABLE #AllRoles
GO
