IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'GetUserAllRights')
	BEGIN
		DROP  Procedure  GetUserAllRights
	END

GO
/***********************************************
***功能描述：获取用户所有的权限，包括继承的和直接授予的
***传入传出参数：
***	@UserID：用户ID
***	@SubSystemID：子系统ID

***作者：
***建立时间:2009-1-6
***更改时间：
***更改人：
***更改原因：
****************************************************/
CREATE PROCEDURE GetUserAllRights
	(
	@SubSystemID VARCHAR(6),
	@UserID int
	)
AS

--建立权限临时表
CREATE TABLE #UserRights(
   RightID              int,
   RightName            varchar(50),
   RightDisplayName     varchar(100),
   RightType			varchar(100),
   RightTypeID			int,
   ParentGroup			varchar(50),
   ParentGroupID		int,
   RightMemo			varchar(1000)
)

DECLARE @GroupID INT
--插入用户的直接拥有的权限
INSERT INTO #UserRights
	SELECT Rights.RightID,Rights.RightName,Rights.RightDisplayName,RightsType.TypeName,RightsType.TypeID,'',0,RightMemo FROM Rights
		INNER JOIN User_Rights
			ON User_Rights.RightID=Rights.RightID
		INNER JOIN RightsType
			ON RightsType.TypeID = Rights.RightTypeID
		WHERE UserID=@UserID AND RightsType.SubSystemID=@SubSystemID

--获取用户直属的所有角色或者组
DECLARE UserGroup CURSOR FOR 
	SELECT GroupID
		FROM User_Group
		WHERE UserID=@UserID
OPEN UserGroup

FETCH NEXT FROM UserGroup INTO @GroupID
WHILE @@FETCH_STATUS = 0
BEGIN
	INSERT INTO #UserRights EXECUTE GetGroupAllRights @SubSystemID,@GroupID
	FETCH NEXT FROM UserGroup INTO @GroupID
END
CLOSE UserGroup
DEALLOCATE UserGroup

-- 返回权限
SELECT DISTINCT * FROM #UserRights ORDER BY RightTypeID