Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop User from SQL Server Database?

How can I drop user from a database without dropping it's logging?

The script should check if the user exists in database, if does then drop the user.

like image 750
sanjeev40084 Avatar asked Jan 07 '10 19:01

sanjeev40084


People also ask

What command would you use to remove a user from a SQL Server?

The DROP USER statement is used to remove a user from the SQL Server database.

How do I drop an orphaned user in SQL Server?

Once you have identified orphan users it is extremely simple to remove them. You remove them by using the sp_revokeuser SP. Here is an example that removes the database users 'USERX', from the current database in use.


2 Answers

Is this what you are trying to do??

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

If you are using SQL Server Management Studio you can browse to the user and right-click selecting delete.

like image 100
doug_w Avatar answered Oct 07 '22 18:10

doug_w


The accepted answer is working good enough. Additionally that is good to know SQL Server added IF EXIST to some DROP commands from version 2016 (13.x) including 'DROP USER' command.

IF EXISTS

Applies to: SQL Server ( SQL Server 2016 (13.x) through current version, SQL Database).

Conditionally drops the user only if it already exists.

So you could just delete user as below:

-- Syntax for SQL Server and Azure SQL Database   DROP USER IF EXISTS user_name   

See the full description in this link: DROP USER (Transact-SQL)

Hope this help.

like image 33
QMaster Avatar answered Oct 07 '22 16:10

QMaster