检查SQL Server数据库中是否存在用户


28

我正在使用SQL Server2012。我想在将用户添加到数据库之前检查用户是否存在。

这是我测试过的:

USE [MyDatabase]
GO

IF NOT EXISTS (SELECT name 
                FROM [sys].[server_principals]
                WHERE name = N'IIS APPPOOL\MyWebApi AppPool')
Begin
    CREATE USER [IIS APPPOOL\MyWebApi AppPool] 
    FOR LOGIN [IIS APPPOOL\MyWebApi AppPool] WITH DEFAULT_SCHEMA=[dbo]
end
ALTER ROLE [db_owner] ADD MEMBER [IIS APPPOOL\MyWebApi AppPool]
GO

但是,SELECT name FROM [sys].[server_principals]如果该用户存在于中,则此代码不会返回MyDatabase

如何检查用户是否存在MyDatabase


1
请记住,sys.database_principals包含角色和用户,因此一定不要忘记过滤用户。我正在针对当前标记的答案更新最终查询,以方便参考。
Moiz Tankiwala

Answers:


26

使用sys.database_principals代替sys.server_principals

因此,最终查询将如下所示(考虑用户过滤器):

USE [MyDatabase]
GO

IF NOT EXISTS (SELECT [name]
                FROM [sys].[database_principals]
                WHERE [type] = N'S' AND [name] = N'IIS APPPOOL\MyWebApi AppPool')
Begin
    CREATE USER [IIS APPPOOL\MyWebApi AppPool] 
    FOR LOGIN [IIS APPPOOL\MyWebApi AppPool] WITH DEFAULT_SCHEMA=[dbo]
end
ALTER ROLE [db_owner] ADD MEMBER [IIS APPPOOL\MyWebApi AppPool]
GO

2
一种获取此错误(或其他对象是否存在检查)的快速方法是右键单击数据库对象,然后选择“ DROP And CREATE TO”,这将生成正确的IF NOT EXISTS子句。
LowlyDBA '16

15

我将SUSER_ID()和USER_ID()用于此类事情:

-- Check SQL Server Login
IF SUSER_ID('SomeLogin') IS NULL
    CREATE LOGIN SomeLogin WITH PASSWORD = 'SomePassword';

-- Check database user
IF USER_ID('SomeUser') IS NULL
    CREATE USER SomeUser FOR LOGIN SomeLogin;

4
根据Microsoft的建议[ docs.microsoft.com/zh-cn/sql/t-sql/functions/…,USER_ID将在不久的将来被淘汰,而推荐使用的功能是DATABASE_PRINCIPAL_ID [ docs.microsoft.com / en-us / sql / t-sql / functions /…
Moiz Tankiwala


9

进一步完善,因为这样可以使阅读效果更好

USE [MyDatabase]
GO

IF DATABASE_PRINCIPAL_ID('IIS APPPOOL\MyWebApi AppPool') IS NULL
BEGIN
    CREATE USER [IIS APPPOOL\MyWebApi AppPool] 
    FOR LOGIN [IIS APPPOOL\MyWebApi AppPool] WITH DEFAULT_SCHEMA=[dbo]
END
ALTER ROLE [db_owner] ADD MEMBER [IIS APPPOOL\MyWebApi AppPool]
GO

0

如果您使用的是拒绝服务器,则可以一次检查许多服务器,并使用以下命令返回true / false:

SELECT @@servername,    
    CASE 
        WHEN EXISTS(SELECT name FROM sys.database_principals WHERE name = 'LoginName') THEN 1 
        ELSE 0 
    END AS YesNo

您可能需要更新答案以提及,database_principals而不是server_principals-检查问题-它与数据库级别的用户有关。
Max Vernon
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.