Using CTE as a block loop ?

二次信任 提交于 2019-12-14 03:16:32

问题


Besides while loop and Cursors

How can I use CTE table to do n block operations ?

for example :

WITH cte AS (
                SELECT 1 AS n
                UNION ALL 
                SELECT n+1
                FROM   cte
                WHERE   n+1<= 10
            )

    INSERT INTO tbl1 (id) select n from cte   --till here it's all ok.
    INSERT INTO tbl2 (id) select n from cte --{notice tbl2} .fail here ( cause cte usages must come right after the decleration)

But is there anything I can do so the second line will be also include ?

p.s. ( beside keeping it as a temp table)


回答1:


In general you can't.

It is only valid for the next statement. You could define a view with the same definition if you want to reuse the definition for multiple statements or materialise it into a temporary table/ table variable yourself to reuse the results.

For the specific case in your question you could do it all in one statement though.

WITH cte
     AS (SELECT 1 AS n
         UNION ALL
         SELECT n + 1
         FROM   cte
         WHERE  n + 1 <= 10)
INSERT INTO tbl1
            (id)
OUTPUT      INSERTED.id
INTO tbl2(id)
SELECT n
FROM   cte 


来源:https://stackoverflow.com/questions/14183678/using-cte-as-a-block-loop

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