Check if role exists in DB?

sanjeev40084 picture sanjeev40084 · Feb 2, 2010 · Viewed 19.6k times · Source

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

Answer

Yada picture Yada · Feb 2, 2010

try:

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