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?
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.
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.
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
if not exists (select 1 from sys.database_principals where name='role' and Type = 'R') begin CREATE ROLE role AUTHORIZATION MyUser; end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With