DB Execute Role Script

  • How can I script this if the role already exists it will not error out, it will skip it? I will still need to sp_addrolemember.

    USE mydb

    GO

    CREATE ROLE db_executor

    GO

    My script:

    ----------------------------------------

    PRINT '--CREATE EXECUTE ROLE'

    select 'USE ' + name +'

    GO' + '

    CREATE ROLE db_executor' +'

    GO' + '

    USE ' + name + '

    GO ' + '

    EXEC sp_addrolemember N''db_executor'', N''mydomain\mygroup''' +'

    GO'

    FROM sys.databases

    where database_id > 4

  • Here you go.

    --- Create Schema/User

    IF EXISTS (SELECT * FROM sys.database_principals WHERE name = N'db_executor' AND type = 'R')

    DROP ROLE [db_executor]

    /* CREATE A NEW ROLE */

    CREATE ROLE db_executor

    Thanks,

    Nikul

  • PERFECT!! Got another one if you're not too busy.

    Do you have a script to loop through the users and logins I want to drop and recreate.

  • EXEC sp_MSforeachdb 'USE ? IF EXISTS

    (SELECT 1 FROM sysusers WHERE name = ''MYDomain\myGroup'') DROP USER [MYDomain\myGroup]'

    Again, Thanks for your help!

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply