create cte multiple times and drop cte [closed]

我怕爱的太早我们不能终老 提交于 2020-01-25 06:45:47

问题


I am using a cte in stored procedure.

I have to use it multiple times ie populate cte for different ids

how can I drop or remove current cte

thanks

;WITH PAYOUT_CTE(REGNKEY, REGNTPE) AS (
    SELECT  REG_KEY, 'Parent'
    FROM    ML_MSTR_REGN A (NOLOCK)
    WHERE   A.COMP_NO = @COMP_NO
        AND     A.REG_KEY = @CUR_KEY

    UNION   ALL

    SELECT  B.REG_KEY, 'Child0'
    FROM    PAYOUT_CTE
    INNER JOIN ML_MSTR_REGN B
        ON  B.COMP_NO = @COMP_NO
           AND  B.ORG_KEY = PAYOUT_CTE.REGNKEY
            )
SELECT * INTO #PAYOUT_CTE_TMP FROM PAYOUT_CTE

I resolved it, as cte is automatically removed after the insert statement only the temp table #PAYOUT_CTE_TMP was causing the problem.


回答1:


The only way I can see this working is if you put the CTE code in a inline table valued function and call that.

Your code would look something like:

CREATE FUNCTION TVFN_PAYOUT_CTE (@COMP_NO INT, @CUR_KEY INT) 
RETURNS TABLE
AS
RETURN (

WITH PAYOUT_CTE(REGNKEY, REGNTPE) AS (
    SELECT  REG_KEY, 'Parent'
    FROM    ML_MSTR_REGN A (NOLOCK)
    WHERE   A.COMP_NO = @COMP_NO
        AND     A.REG_KEY = @CUR_KEY

    UNION   ALL

    SELECT  B.REG_KEY, 'Child0'
    FROM    PAYOUT_CTE
    INNER JOIN ML_MSTR_REGN B
        ON  B.COMP_NO = @COMP_NO
           AND  B.ORG_KEY = PAYOUT_CTE.REGNKEY
            )
SELECT * 
FROM PAYOUT_CTE
)

Then I can just cross apply or outer apply to this table valued function to generate data based on input values.

If COMP_NO and CUR_KEY are values in a "TEST" table, I could use each of the rows with COMP_NO and CUR_KEY to run the CTE with those values and save them, like below:

SELECT PC.*
    INTO #PAYOUT_CTE_TMP
FROM TEST T
    CROSS APPLY TVFN_PAYOUT_CTE (T.COMP_NO, T.CUR_KEY) PC

By doing this, the CTE is rebuilt and ran for each row from the TEST table.



来源:https://stackoverflow.com/questions/48003428/create-cte-multiple-times-and-drop-cte

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!