如何优化SQL Server中的CTE

时间:2013-05-23 08:58:46

标签: sql sql-server query-optimization recursive-query

下面是我的递归查询,以获取每个孩子的孩子和孩子,但执行时间太长。如何优化此查询以便更快地执行。如果我删除distinct,它会带来多条记录。

        DECLARE @int_UserID INT
    DECLARE @ProjectID INT
    SET @int_UserID=74
    SET @ProjectID=96


    ;WITH Records AS (
            SELECT pu.int_USER_ID,alh.int_Level_ID 
            FROM tbl_PROJECT_USER pu INNER JOIN tbl_Project_User_Role pur ON pu.int_USER_ROLE =     pur.int_Project_User_Role_ID
            INNER JOIN tbl_Access_Level_Hierarchy alh ON   pur.int_Access_Level_IDRef=alh.int_Level_ID
            INNER JOIN tbl_USER u ON u.int_USER_ID=pu.int_USER_ID
            WHERE pu.int_USER_ID=@int_UserID AND pu.int_PROJECT_ID=@ProjectID

            UNION ALL
            SELECT pu.int_USER_ID,alh.int_Level_ID 
            FROM tbl_PROJECT_USER pu INNER JOIN tbl_Project_User_Role pur ON pu.int_USER_ROLE =    pur.int_Project_User_Role_ID
            INNER JOIN tbl_Access_Level_Hierarchy alh ON pur.int_Access_Level_IDRef=alh.int_Level_ID
            INNER JOIN Records R ON R.int_Level_ID=alh.int_Level_Order 
            WHERE pu.int_PROJECT_ID=@ProjectID 
    )
    SELECT DISTINCT * FROM Records
    OPTION(MAXRECURSION 0)

感谢所有人。 通过改变一些逻辑,我得到了最佳解决方案。

0 个答案:

没有答案