如何在 SQL Server 中测试用户是否存在? [英] How do you test for the existence of a user in SQL Server?

查看:43
本文介绍了如何在 SQL Server 中测试用户是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 SQL Server 脚本中删除一个用户,但我需要先测试是否存在,否则我会收到脚本错误.删除表或存储过程时,我会像这样检查 sysobjects 表:

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.

推荐答案

SSMS 按照以下方式编写脚本:

SSMS scripts it in the following way:

对于 SQL 2005/2008:

For SQL 2005/2008:

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

对于 SQL 2000:

For SQL 2000:

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

这篇关于如何在 SQL Server 中测试用户是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆