Search code examples
sqlsql-serverdatabasepermissionsroles

Check if role exists in DB?


I want to add users to the same role in more than one database. However the role may or may not be present in each database. How can I check if the role exists in each database and if it does, add users to that role?

e.g. IF role exists BEGIN Add user in role END


Solution

  • try:

    IF DATABASE_PRINCIPAL_ID('role') IS NULL
    BEGIN
      -- add user here
      CREATE ROLE role AUTHORIZATION MyUser;
    END