tags:

views:

576

answers:

2

I'm trying to figure out how I can check if a database role exists in SQL Server. I want to do something like this:

if not exists (select 1 from sometable where rolename='role')
begin
CREATE ROLE role
    AUTHORIZATION MyUser;
end

What table/proc should I use here?

+3  A: 
SELECT DATABASE_PRINCIPAL_ID('role')
--or
IF DATABASE_PRINCIPAL_ID('role') IS NULL

USER_ID is deprecated and could break. CREATE ROLE indicates SQL 2005+ so it's OK

gbn
+2  A: 
if not exists (select 1 from sys.database_principals where name='role' and Type = 'R')
begin
CREATE ROLE role
    AUTHORIZATION MyUser;
end
G Mastros
This fails if you have a user who happens to have the same "role" name. Odd, but you'd have to remove the "= 'R'" to work 100%
gbn