Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you test for the existence of a user in SQL Server?

Tags:

I'd like to drop a user in a SQL Server script but I'll need to test for existence first or I'll get script errors. When dropping tables or stored procs, I check the sysobjects table like so:

IF EXISTS (     SELECT *      FROM   sysobjects      WHERE  id = object_id(N'[dbo].[up_SetMedOptions]')      AND    OBJECTPROPERTY(id, N'IsProcedure') = 1 ) Drop Procedure up_SetMedOptions; GO 

What is the corollary for checking for a user? Note that I am NOT asking about a database login to the server! The question pertains to a User in a specific database.

like image 657
Mark Brittingham Avatar asked Dec 10 '08 13:12

Mark Brittingham


People also ask

How do you check if a user exists in a database?

To check how many users are present in MySQL, use MySQL. user table. The syntax is as follows to check how many users are present. Now you can check and drop the user if it exist.

Which operator is used to check for existence of a value in SQL?

If you need to check for existence of values in another table, the EXISTS operator is preferred as it clearly demonstrates the intent of the query.


1 Answers

SSMS scripts it in the following way:

For SQL 2005/2008 and later:

IF  EXISTS (SELECT * FROM sys.database_principals WHERE name = N'username') DROP USER [username] 

For SQL 2000:

IF  EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'username') EXEC dbo.sp_revokedbaccess N'username' 
like image 197
Ed Harper Avatar answered Oct 01 '22 03:10

Ed Harper