Hi, Peter.
> I just realize that using those views are more complicated since the user
> and the desired role may be related thru a hierarchy not a direct
> relationship.
The CTE below ought to identify indirect membership:
WITH role_hierarchy
AS
(
SELECT
rm.member_principal_id,
rm.role_principal_id
FROM sys.database_role_members rm
WHERE
rm.role_principal_id = USER_ID('role_name')
UNION ALL
SELECT
rm.member_principal_id,
rm.role_principal_id
FROM sys.database_role_members rm
JOIN role_hierarchy rh ON
rh.member_principal_id = rm.role_principal_id
)
SELECT 'is a member' FROM role_hierarchy rh
WHERE USER_NAME(rh.member_principal_id) = 'user_name';

Signature
Hope this helps.
Dan Guzman
SQL Server MVP
http://weblogs.sqlteam.com/dang/
Peter - 27 Aug 2008 03:31 GMT
Thanks Dan. Will try it.
> Hi, Peter.
>
[quoted text clipped - 23 lines]
> SELECT 'is a member' FROM role_hierarchy rh
> WHERE USER_NAME(rh.member_principal_id) = 'user_name';
Peter - 28 Aug 2008 19:45 GMT
Hi Dan,
The CTE works. I have never used CTE before. I create the following user
function temporarily to see how I can use the CTE in a function. I just have
the parameter for the user but will add the parameter for the role later.
Does it look like the correct way to implement the function with the CTE?
Thanks.
CREATE function [dbo].[check_role](@user varchar(100))
returns bit
as begin
declare @bexist bit
select @bexist = 0;
WITH role_hierarchy
AS
(
SELECT
rm.member_principal_id,
rm.role_principal_id
FROM sys.database_role_members rm
WHERE
rm.role_principal_id = USER_ID('SQLAgentUserRole')
UNION ALL
SELECT
rm.member_principal_id,
rm.role_principal_id
FROM sys.database_role_members rm
JOIN role_hierarchy rh ON
rh.member_principal_id = rm.role_principal_id
)
SELECT @bexist = 1 FROM role_hierarchy rh
WHERE USER_NAME(rh.member_principal_id) = @user
return @bexist
end
> Hi, Peter.
>
[quoted text clipped - 23 lines]
> SELECT 'is a member' FROM role_hierarchy rh
> WHERE USER_NAME(rh.member_principal_id) = 'user_name';
Dan Guzman - 29 Aug 2008 02:02 GMT
> Does it look like the correct way to implement the function with the CTE?
Yes, I think your function will return the desired result.

Signature
Hope this helps.
Dan Guzman
SQL Server MVP
http://weblogs.sqlteam.com/dang/
> Hi Dan,
>
[quoted text clipped - 61 lines]
>> SELECT 'is a member' FROM role_hierarchy rh
>> WHERE USER_NAME(rh.member_principal_id) = 'user_name';