一尘不染

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

sql

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

这是我测试过的:

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


阅读 71

收藏
2022-11-01

共1个答案

一尘不染

使用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
2022-11-01