如何测试SQL Server中是否存在用户?

时间:2023-02-08 16:32:53

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:

我想在SQL Server脚本中删除用户,但我需要先测试存在,否则我会收到脚本错误。当删除表或存储过程时,我检查sysobjects表,如下所示:

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.

检查用户的必然结果是什么?请注意,我不是要求数据库登录到服务器!该问题与特定数据库中的用户有关。

3 个解决方案

#1


32  

SSMS scripts it in the following way:

SSMS以下列方式编写脚本:

For SQL 2005/2008:

对于SQL 2005/2008:

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

For SQL 2000:

对于SQL 2000:

IF  EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'username')
EXEC dbo.sp_revokedbaccess N'username'

#2


2  

In SQL 2005:

在SQL 2005中:

select * from sys.sysusers

In SQL 2000:

在SQL 2000中:

select * from sysusers

#3


-1  

The code below worked for me.

下面的代码对我有用。

IF EXISTS (SELECT * FROM sys.syslogins WHERE name = N'MyUserName') 
DROP LOGIN [MyUserName]

#1


32  

SSMS scripts it in the following way:

SSMS以下列方式编写脚本:

For SQL 2005/2008:

对于SQL 2005/2008:

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

For SQL 2000:

对于SQL 2000:

IF  EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'username')
EXEC dbo.sp_revokedbaccess N'username'

#2


2  

In SQL 2005:

在SQL 2005中:

select * from sys.sysusers

In SQL 2000:

在SQL 2000中:

select * from sysusers

#3


-1  

The code below worked for me.

下面的代码对我有用。

IF EXISTS (SELECT * FROM sys.syslogins WHERE name = N'MyUserName') 
DROP LOGIN [MyUserName]