0

如果数据库中尚不存在用户,我将使用以下内容创建用户:

use DBExample
GO

IF NOT EXISTS (SELECT * from sys.database_role_members WHERE USER_NAME(member_principal_id) = 'user1')
BEGIN
CREATE USER [user1] WITH PASSWORD = 'abc')
END

EXEC sp_addrolemember 'role1', 'user1'
GO

DBExample 已经有一个 user1,因此当我尝试运行该脚本时,SQL Server Management Studio 会抱怨“'user1' 附近的语法不正确”。(在创建用户行中)

我缺少什么来完成这项工作?

4

2 回答 2

2

我认为您对此感到困惑Logins-Users至少在 SQL Server 2008R2 中,您不能没有另一个。我建议您快速浏览一下联机丛书以了解这些概念。

您可能正在寻找类似的东西:

IF NOT EXISTS (SELECT * from sys.server_principals WHERE name = 'user1')
BEGIN
CREATE LOGIN [user1] WITH PASSWORD = 'abc';
END
GO  

USE DBExample
GO

IF NOT EXISTS
(
  SELECT * from sys.database_principals dp
  INNER JOIN sys.server_principals sp on dp.sid = sp.sid
  WHERE dp.name = 'user1' or sp.name = 'user1'
)
BEGIN
CREATE USER [user1] FOR LOGIN [user1]
END
GO

IF NOT EXISTS (SELECT * from sys.database_role_members WHERE USER_NAME(member_principal_id) = 'user1')
BEGIN
EXEC sp_addrolemember 'role1', 'user1'
END

GO

Login如果它不存在,则创建 a,然后转到数据库,然后如果它不存在则创建 a ,然后将 a与 aUser关联。UserRole

于 2013-02-04T17:32:38.590 回答
0

I used the answer found here: https://stackoverflow.com/a/6159882 to make use of variables to substitute the user name to get around the 'There is already login/user named xxx in the database' error SSMS was complaining about. The code looks like this at the end:

USE DBExample
GO

DECLARE @userName varchar(100)

SET @userName = 'user1'

IF NOT EXISTS (SELECT * from sys.server_principals WHERE name = @userName)
BEGIN
DECLARE @LoginSQL varchar(200);
SET @LoginSQL = 'CREATE LOGIN ' + @userName + ' WITH PASSWORD = abc';
EXEC (@LoginSQL);
END

IF NOT EXISTS (SELECT * from sys.database_principals WHERE name = @userName)
BEGIN
DECLARE @UserSQL varchar(200);
SET @UserSQL = 'CREATE USER ' + @userName + ' FOR LOGIN ' + @userName;
EXEC (@UserSQL);
END

IF NOT EXISTS (SELECT * from sys.database_role_members WHERE USER_NAME(member_principal_id) = @userName)
BEGIN
EXEC sp_addrolemember 'role1', @userName
END

GO
于 2013-02-04T18:01:49.430 回答