检查是否已存在SQL Server登录名 [英] Checking if a SQL Server login already exists

查看:239
本文介绍了检查是否已存在SQL Server登录名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查SQL Server上是否已经存在特定的登录名,如果不存在,则需要添加它.

I need to check if a specific login already exists on the SQL Server, and if it doesn't, then I need to add it.

我发现以下代码可以将登录名实际添加到数据库中,但是我想将其包装在IF语句中(以某种方式)以检查登录名是否首先存在.

I have found the following code to actually add the login to the database, but I want to wrap this in an IF statement (somehow) to check if the login exists first.

CREATE LOGIN [myUsername] WITH PASSWORD=N'myPassword', 
DEFAULT_LANGUAGE=[us_english], 
CHECK_EXPIRATION=OFF, 
CHECK_POLICY=OFF 
GO

我了解我需要查询系统数据库,但不确定从哪里开始!

I understand that I need to interrogate a system database, but not sure where to start!

推荐答案

来自此处

If not Exists (select loginname from master.dbo.syslogins 
    where name = @loginName and dbname = 'PUBS')
Begin
    Select @SqlStatement = 'CREATE LOGIN ' + QUOTENAME(@loginName) + ' 
    FROM WINDOWS WITH DEFAULT_DATABASE=[PUBS], DEFAULT_LANGUAGE=[us_english]')

    EXEC sp_executesql @SqlStatement
End

这篇关于检查是否已存在SQL Server登录名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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