Reuse results from SQL Server common table expression

前端 未结 3 1583
悲&欢浪女
悲&欢浪女 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条回答
  •  梦毁少年i
    2021-01-22 07:39

    From the WITH common_table_expression manual:

    Specifies a temporary named result set, known as a common table expression (CTE). This is derived from a simple query and defined within the execution scope of a single SELECT, INSERT, UPDATE, or DELETE statement.

    So, no, you can't extend the scope of the CTE beyond the SELECT statement it was defined in. You will have to store the result in a temporary table or table valued variable if you want to use the result more than once.

提交回复
热议问题