2016-09-29 45 views
1

我正在處理腳本以將登錄名添加到用戶定義的角色,其中需要輸入RoleNameLogin作爲輸入參數。檢查用戶定義的數據庫角色中是否已添加登錄名

檢查在添加之前是否已經存在,但下面的檢查返回NULL。

USE [MYDatabase]; 
DECLARE @AddUser NVARCHAR(100) = 'test' 
DECLARE @RoleName NVARCHAR(100) = 'MYDatabase_ReadOnly' -- User Defined DB ROle 
IF EXISTS (Select name from sys.database_principals where name = @RoleName) 
BEGIN 
    SELECT IS_SRVROLEMEMBER (@RoleName, @AddUser) 
    --Output: NULL 
END 

我可以看到兩個testMYDatabase_ReadOnlysys.database_principals可用。

我在這裏失蹤了什麼?

+0

'sys.database_principals','S'或'U'中的用戶是什麼'type'? 'test'的 – HABO

+0

類型是'S'。 – p2k

回答

0

它必須是IS_ROLEMEMBER(@RoleName, @AddUser)因爲它正在檢查數據庫角色,而不是IS_SRVROLEMEMBER (@RoleName, @AddUser)(我在SQL Server 2014這樣做)。

0
--Syntax: IS_SRVROLEMEMBER ('role' [ , 'login' ]) 
--Return value as NULL indicates role or login is not valid, or you do not have permission to view the role membership 
--Return value as 0 indicates login is not a member of role. 
--Return value as 1 indicates login is a member of role. 

--I think you are using rong value for role paramenter.(Use role value from below) 
--sysadmin,bcreator,bulkadmin,diskadmin,public,processadmin 

USE [MYDatabase]; 
DECLARE @database_principals_name NVARCHAR(100) = 'db_owner' 
DECLARE @RoleName NVARCHAR(100) = 'sysadmin' -- User Defined DB ROle 
IF EXISTS (Select name from sys.database_principals where name = @database_principals_name) 
BEGIN 
    select IS_SRVROLEMEMBER ('sysadmin') 
    --Output: NULL 
END 
相關問題