我正在使用 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.
SELECT name FROM [sys].[server_principals]
MyDatabase
如何检查用户是否存在MyDatabase?
使用sys.database_principals而不是sys.server_principals.
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