Insert Into Table Variable CTE

后端 未结 2 822
南笙
南笙 2021-01-21 21:56

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

Something like this?

DECLARE
       @myData TABLE( 
                        Title nvarchar(350)          


        
相关标签:
2条回答
  • 2021-01-21 22:04

    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
    
    0 讨论(0)
  • 2021-01-21 22:18

    On my SQL2019 edition, the above construct yield no fields inserted. Even worse, if I wanted to use UPDATE after the statement, gave a syntax error.

    Instead, this construct was working also in a stored procedure:

    ; WITH CTE AS (
      select ...
      UNION ALL
      select ...
    )
    insert into @tableVariable(fields..) (select field... from CTE)
    

    Hope somebody will make use of this.

    0 讨论(0)
提交回复
热议问题