Reuse results from SQL Server common table expression

前端 未结 3 1587
悲&欢浪女
悲&欢浪女 2021-01-22 07:16

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?

3条回答
  •  余生分开走
    2021-01-22 07:41

    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
    )
    

提交回复
热议问题