更新时避免使用游标

时间:2017-03-19 16:20:40

标签: sql sql-server sql-server-2008

+--------+-----------+-------+
| PartId | InvoiceId | Price |
+--------+-----------+-------+
|  200   |   1000    | 10000 |
|  201   |   1001    | 22000 |
|  202   |   1002    | 30000 |
+--------+-----------+-------+

+--------+-----------+-------+
| PartId | PaymentId | Price |
+--------+-----------+-------+
|  200   |   1000    | 1000  |
|  200   |   1001    | 3000  |
|  201   |   1002    | 5000  |
+--------+-----------+-------+

+-----------+-----------+-------------------------+
| InvoiceId | PaymentId | Balance Need to be Paid |
+-----------+-----------+-------------------------+
|  1000     |   1000    | 9000                    |
|  1000     |   1001    | 6000                    |
|  1001     |   1002    | 17000                   |
+-----------+-----------+-------------------------+

由于游标性能不太好,不使用游标是否有任何可能的方法来更新发票付款映射表?

1 个答案:

答案 0 :(得分:1)

您可以在一次更新中执行此操作。以下是相当推测的,因为你的问题没有所有必要的细节。您可以在join查询中使用update

update ip
    set BalanceToBePaid = (i.price - p.sumprice)
from invoicepayment ip join
     invoices i
     on ip.invoiceid = i.invoiceid join
     (select paymentid, sum(price) as sumprice
      from payments
      group by paymentid
    ) p
    on ip.payment = p.payment;
相关问题