views:

330

answers:

3

I want to add users in same role in more than one database. However the role can/cannot be present in all the database. How can i check if the role exists in database and if it does add users in that role?

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

+2  A: 

try:

IF DATABASE_PRINCIPAL_ID('role') IS NULL
BEGIN
  -- add user here
  CREATE ROLE role AUTHORIZATION MyUser;
END
Yada
+1  A: 
IF EXISTS 
(
  SELECT 1
    FROM sys.database_principals
    WHERE type_desc = 'DATABASE_ROLE'
    AND name = 'name'
)
BEGIN
  -- add user;
END
Aaron Bertrand
A: 

Please refer to this link. Probably the same thing you're looking for

http://stackoverflow.com/questions/1201160/how-do-i-determine-if-a-database-role-exists-in-sql-server

madatanic