Check if a user exists in a SQL Server database
Use sys.database_principals
instead of sys.server_principals
.
So the final query would look like this (accounting for the user filter):
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
I use SUSER_ID() and USER_ID() for this kind of things:
-- 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;
Further refinement as this would make a more optimal read-
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