views:

70

answers:

2

I have a table Users with columns

ID nvarchar(4000)
GroupRank int
Definition nvarchar(4000)

ID can be a userid (in which case groupRank is NULL), a domain group with a rank (in which case grouprank is not null) or a reserved default group called #DefaultGroup.

I need a stored procedure that will:

If ID=SYSTEM_USER, return that Definition

Otherwise - foreach record in Users with GroupRank NOT NULL in order of group rank, if IS_MEMBER(ID) =1, that definition (if any)

Otherwise - the #DefaultGroup definition (if it's there)

Otherwise return NULL.

Is there an easy way to do this?

+2  A: 

If I'm understanding you correctly, you might be able to use some sort of case statement similar to the one below:

SELECT
  ID,
  GroupRank,
  Definition = CASE
                WHEN ID = SYSTEM_USER THEN Definition
                WHEN GroupRank IS NOT NULL AND IS_MEMBER(ID) = 1 THEN Definition
                WHEN ID = '#DefaultGroup' THEN Definition
                ELSE NULL
               END
FROM
     [YourTable]
Jose Basilio
Would this resolve the case where a user is a member of multiple groups?
WOPR
A: 

This seems to work as a table function

CREATE FUNCTION dbo.GetDefinition()
RETURNS @definition TABLE 
(
    Defn nvarchar(4000) NULL 
)
AS 
BEGIN
    DECLARE @sys_usr nvarchar(4000);
    DECLARE @def_usr nvarchar(4000);
    SET @sys_usr = SYSTEM_USER;
    SET @def_usr = '#Default';

    IF(EXISTS(SELECT * FROM dbo.User WHERE ID = @sys_usr))
    BEGIN
        INSERT @definition SELECT Definition FROM User WHERE ID = @sys_usr
    END ELSE
    BEGIN
     IF(EXISTS(SELECT TOP 1 * FROM dbo.User WHERE IS_MEMBER(ID) = 1 AND GroupRank IS NOT NULL ORDER BY GroupRank))
     BEGIN
      INSERT @definition SELECT TOP 1 Definition FROM dbo.User 
       WHERE IS_MEMBER(ID) = 1 AND GroupRank IS NOT NULL ORDER BY GroupRank
     END ELSE
     BEGIN
      IF(EXISTS(SELECT * FROM dbo.User WHERE ID = @def_usr))
      BEGIN
       INSERT @definition SELECT Definition FROM User WHERE ID = @def_usr
      END
     END
    END

    RETURN;
END
WOPR