如果用户在数据库中已经存在,我将使用以下内容创建用户:
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'”附近抱怨“语法错误”。 (在创建用户行中)
我缺少什么让这项工作?
答案 0 :(得分: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
,如果不存在,则转到数据库然后创建User
,然后将User
与{{1}关联}}
答案 1 :(得分:0)
我使用了这里找到的答案:https://stackoverflow.com/a/6159882利用变量替换用户名来解决“数据库中已存在登录/用户名为xxx”错误SSMS抱怨的问题。代码在最后看起来像这样:
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