Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

sql-server

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?

like image 543
Jon Kruger Avatar asked Jul 29 '09 15:07

Jon Kruger


People also ask

How can I see roles in SQL Server?

Listing SQL Server roles for a userIn the Server type list box, select Database Engine. In the Server name text box, type the name of the SQL cluster server. In the Authentication list box, choose your SQL Server Authentication method and specify the credentials to use.

How do you check what roles are assigned to a user in SQL?

To find all the role assignments to users in SQL Server database, you can use the following query. SELECT r.name role_principal_name, m.name AS member_principal_name FROM sys. database_role_members rm JOIN sys. database_principals r ON rm.


2 Answers

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

like image 94
gbn Avatar answered Oct 14 '22 04:10

gbn


if not exists (select 1 from sys.database_principals where name='role' and Type = 'R') begin CREATE ROLE role     AUTHORIZATION MyUser; end 
like image 31
George Mastros Avatar answered Oct 14 '22 04:10

George Mastros