Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update records in table from CTE

I have the following CTE that will give me the DocTotal for the entire invoice.

 ;WITH CTE_DocTotal  AS  (    SELECT SUM(Sale + VAT) AS DocTotal    FROM PEDI_InvoiceDetail    GROUP BY InvoiceNumber  )  UPDATE PEDI_InvoiceDetail SET DocTotal = CTE_DocTotal.DocTotal 

Now with this result I want to enter into the column the DocTotal value inside PEDI_InvoiceDetail.

I know is not going to work and I know I am missing something, what is it?

like image 981
Etienne Avatar asked Jul 19 '12 14:07

Etienne


People also ask

Can we perform DML on CTE?

CTE can be used for both selects and DML (Insert, Update, and Delete) statements.

Can we insert data using CTE?

You can also use CTE to insert data into the SQL table. The CTE query definition includes the required data that you can fetch from existing tables using joins. Later, query CTE for inserting data into the target table.


1 Answers

Updates you make to the CTE will be cascaded to the source table.

I have had to guess at your schema slightly, but something like this should work.

;WITH T AS (   SELECT  InvoiceNumber,              DocTotal,              SUM(Sale + VAT) OVER(PARTITION BY InvoiceNumber) AS NewDocTotal     FROM    PEDI_InvoiceDetail ) UPDATE  T SET     DocTotal = NewDocTotal 
like image 113
GarethD Avatar answered Sep 19 '22 18:09

GarethD