How to reference one CTE twice?

后端 未结 5 1441
粉色の甜心
粉色の甜心 2020-12-15 17:44

I have a very fat common table expression which includes row numbers so that I can return a paged result set. I also want to return the total number of records that match th

5条回答
  •  时光说笑
    2020-12-15 18:15

    Don't think you can. From MSDN

    A common table expression (CTE) can be thought of as a temporary result set that is defined within the execution scope of a single SELECT, INSERT, UPDATE, DELETE, or CREATE VIEW statement.

    Emphasis on "single SELECT, INSERT, UPDATE, DELETE, or CREATE VIEW statement."

    This might be a situation where you want to use a Temporary Table.

    CREATE TABLE #Recs
    {
      .....
    }
    INSERT INTO #Recs
    select *, row_number() over (order by id) as rownum from ......
    

    If you don't know the structure of the table before hand you can use this form to create a temporary table:

    select *, row_number() over (order by id) as rownum INTO #Recs from ......
    

    You will be able to use the Temporary table in the manner you have described above.

提交回复
热议问题