从CTE更新表中的logging

我有以下CTE将给我整个发票的DocTotal。

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

现在有了这个结果,我想进入PEDI_InvoiceDetail里的DocTotal值列。

我知道不会工作,我知道我错过了什么,是什么?

您对CTE所做的更新将被级联到源表。

我不得不稍微猜测你的模式,但是这样的事情应该可以工作。

 ;WITH T AS ( SELECT InvoiceNumber, DocTotal, SUM(Sale + VAT) OVER(PARTITION BY InvoiceNumber) AS NewDocTotal FROM PEDI_InvoiceDetail ) UPDATE T SET DocTotal = NewDocTotal 
 WITH CTE_DocTotal (DocTotal, InvoiceNumber) AS ( SELECT InvoiceNumber, SUM(Sale + VAT) AS DocTotal FROM PEDI_InvoiceDetail GROUP BY InvoiceNumber ) UPDATE PEDI_InvoiceDetail SET PEDI_InvoiceDetail.DocTotal = CTE_DocTotal.DocTotal FROM CTE_DocTotal INNER JOIN PEDI_InvoiceDetail ON ... 

你不需要CTE

 UPDATE PEDI_InvoiceDetail SET DocTotal = v.DocTotal FROM PEDI_InvoiceDetail inner join ( SELECT InvoiceNumber, SUM(Sale + VAT) AS DocTotal FROM PEDI_InvoiceDetail GROUP BY InvoiceNumber ) v ON PEDI_InvoiceDetail.InvoiceNumber = v.InvoiceNumber 

尝试以下查询:

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