0

I have a stored procedure with multiple CTE's where I am trying to insert the outcome in to a table. I have tried following the guidance here Combining INSERT INTO and WITH/CTE but having no luck. Could someone advise where to put the INSERT please?

AS BEGIN

With CTE1 As (

    Query

 ),

  CTE2 As (
     
   Query

),

  CTE3 As  (

   Query
)


INSERT INTO dbo.table

(

Fields

)

Select * From 

(

Select * from CTE1

Union

Select * from CTE2

Union 

Select * from CTE3

) as A

END
;
whitz11
  • 229
  • 2
  • 23
  • what error do you get? – TZHX Sep 06 '22 at 15:06
  • There is no such thing as "SSMS 2018", and it doesn't help us understand what RDBMS you are using other than it's a Microsoft product; SQL Server? Azure SQL Database? Azure Synapse? Those CTE declarations aren't valid either. `WITH` only goes at the *start* of the statement, not every single CTE alias. `WITH CTE1 AS (...),CTE2 AS(...) SELECT ... FROM CTE1...` You also have a random `END` at the end up your batch, but no related `BEGIN`. – Thom A Sep 06 '22 at 15:06
  • @TZHX Invalid object name 'CTE1' – whitz11 Sep 06 '22 at 15:17

0 Answers0