patternsqlMajor
Check if a user exists in a SQL Server database
Viewed 0 times
sqluserdatabaseexistsservercheck
Problem
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:
But, this code
How can I check if an user exists in
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]
GOBut, 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?Solution
Use
So the final query would look like this (accounting for the user filter):
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]
GOCode Snippets
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]
GOContext
StackExchange Database Administrators Q#125886, answer score: 45
Revisions (0)
No revisions yet.