2013-02-04 45 views
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'附近有'錯誤的語法。 (在創建用戶行中)

我錯過了什麼使其工作?

回答

0

我用這裏找到的答案:https://stackoverflow.com/a/6159882來利用變量來替換用戶名,以避開SSMS抱怨的'數據庫中已經存在名爲xxx的登錄名/用戶'錯誤。該代碼看起來是這樣結尾:

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 
2

我認爲你很困惑LoginsUsers - 在SQL Server 2008R2中,至少,你不能沒有其他的。我建議快速瀏覽一下Books Online的這些概念。

你可能尋找類似:

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如果它不存在,那麼相關聯的UserRole

+0

我得到一個錯誤說「已經有登入數據庫名爲‘user1的’ – confusedKid

+0

好吧,我懷疑已經有映射到數據庫用戶* USER1 *。我已經更新了代碼來處理這種情況。 –