Insert Into Table Variable CTE

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-20 03:18:09

问题


How to insert the results of a cte into a table variable

Something like this?

DECLARE
       @myData TABLE( 
                        Title nvarchar(350) NOT NULL , 
                        Id int NOT NULL ,
                    );
INSERT INTO @myData

with CTE as 
    (SELECT       
      a.Title 
     ,a.Id
  FROM
       TableA
     )
    ,CTE2 as 
    (SELECT  
      b.Title
     ,b.Id   
  FROM
       TableB
    )

    Select * From CTE

    union all

    Select * From CTE2

    Select  ROW_NUMBER() OVER(ORDER BY GetDate() DESC) AS RowId
       , x.* 
       From @myData x
       order by x.Id desc

回答1:


Try this

with CTE as 
    (SELECT       
      a.Title 
     ,a.Id
  FROM
       TableA
     )
    ,CTE2 as 
    (SELECT  
      b.Title
     ,b.Id   
  FROM
       TableB
    )
    INSERT INTO @myData  --- insert statement goes here after CTE

    Select * From CTE    
    union all    
    Select * From CTE2

    Select  ROW_NUMBER() OVER(ORDER BY GetDate() DESC) AS RowId, x.* 
    From @myData x
    order by x.Id desc


来源:https://stackoverflow.com/questions/23026240/insert-into-table-variable-cte

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