I have a query to retrieve all the modules and child modules for a page, using a common table expression. Is it possible to use the results from the cte more than once?
Use like following :
Create FUNCTION [dbo].[fnGetAllData]
(
@UserId int
)
RETURNS TABLE
AS
RETURN
(
WITH UserPRecursive AS
(
SELECT u.userid,u.OverrideID
FROM UserOverride u where OverrideID=@UserId
UNION ALL
SELECT C.userid,C.OverrideID
FROM UserOverride AS C INNER JOIN UserPRecursive AS cr
ON C.OverrideID = cr.userid
)
, UserCRecursive AS
(
SELECT u.userid,u.OverrideID
FROM UserOverride u where UserID=@UserId
UNION ALL
SELECT C.userid,C.OverrideID
FROM UserOverride AS C INNER JOIN UserCRecursive AS cr
ON C.userid = cr.OverrideID
)
SELECT distinct CR1.userid as userId FROM UserPRecursive AS CR1
UNION ALL
SELECT distinct cr2.OverrideID as userId FROM UserCRecursive AS CR2
UNION ALL
select userid from [User] where UserID=@UserId
)