How do I determine if a database role exists in SQL Server?

SqlSql Server

Sql Problem Overview


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?

Sql Solutions


Solution 1 - Sql

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

Solution 2 - Sql

if not exists (select 1 from sys.database_principals where name='role' and Type = 'R')
begin
CREATE ROLE role
    AUTHORIZATION MyUser;
end

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJon KrugerView Question on Stackoverflow
Solution 1 - SqlgbnView Answer on Stackoverflow
Solution 2 - SqlGeorge MastrosView Answer on Stackoverflow