从CTE更新表中的记录

时间:2012-07-19 14:01:08

标签: sql sql-server tsql common-table-expression

我有以下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值。

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

4 个答案:

答案 0 :(得分:94)

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

我不得不稍微猜测你的架构,但这样的事情应该有用。

;WITH T AS
(   SELECT  InvoiceNumber, 
            DocTotal, 
            SUM(Sale + VAT) OVER(PARTITION BY InvoiceNumber) AS NewDocTotal
    FROM    PEDI_InvoiceDetail
)
UPDATE  T
SET     DocTotal = NewDocTotal

答案 1 :(得分:28)

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 ...

答案 2 :(得分:21)

您不需要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

答案 3 :(得分:0)

尝试以下查询:

Select FirstName FROM Contact WHERE  MobilePhone = '04123456789'