如何确定 SQL Server 中是否存在数据库角色?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1201160/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 03:00:42  来源:igfitidea点击:

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

sqlsql-server

提问by Jon Kruger

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:

我想弄清楚如何检查 SQL Server 中是否存在数据库角色。我想做这样的事情:

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

What table/proc should I use here?

我应该在这里使用什么表/过程?

回答by gbn

SELECT DATABASE_PRINCIPAL_ID('role')
--or
IF DATABASE_PRINCIPAL_ID('role') IS NULL

USER_IDis deprecated and could break. CREATE ROLEindicates SQL 2005+ so it's OK

USER_ID已弃用,可能会中断。CREATE ROLE表示 SQL 2005+ 所以没问题

回答by George Mastros

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