I'm working with SQL Server 2012. I want to check if a user exists before adding it to a database.
This is what I have tested:
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
But, this code SELECT name FROM [sys].[server_principals]
doesn't return if that user exists in MyDatabase
.
How can I check if an user exists in MyDatabase
?