22

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.

Tom Halladay
  • 5,651
  • 6
  • 46
  • 65
Mark Brittingham
  • 28,545
  • 12
  • 80
  • 110

3 Answers3

33

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'
Ed Harper
  • 21,127
  • 4
  • 54
  • 80
2

In SQL 2005:

select * from sys.sysusers

In SQL 2000:

select * from sysusers
edosoft
  • 17,121
  • 25
  • 77
  • 111
-1

The code below worked for me.

IF EXISTS (SELECT * FROM sys.syslogins WHERE name = N'MyUserName') 
DROP LOGIN [MyUserName]
Diganta Kumar
  • 3,637
  • 3
  • 27
  • 29
  • 3
    The question specifically says "I am **NOT** asking about a database **login** to the server". Your solution will remove a **login** and leave an orphaned database **user**. – Paul Sturm Nov 13 '14 at 13:52