0

I have tried to run an update on a list of records and modify a column based on a few calculations. This is my query (my query actually does a redistribution of amounts into NET and VAT):

update transaction_details
set amount = (
    CASE WHEN id = x.netID THEN x.calculated_NET
         WHEN id = x.vatID THEN x.calculated_VAT
    END
    )
from
    (select
        d1.id as 'netHmy',
        d2.id as 'vatHmy',
        round(((d1.amount + d2.amount )/1.18) * 0.18, 2) 'calculated_VAT',
        round((d1.amount + d2.amount )/1.18, 2) 'calculated_NET'
    from transaction_details d1 join transaction_details d2 on d1.id = d2.netID
    where
        1 = 1
        -- multiple conditions
                              ) as x

The records selected into X table are 175, but when I run this query it goes over the entire transaction_details table (over 4.000.000 records).

I know that the order of operations in a query is

1. FROM clause
2. WHERE clause
3. GROUP BY clause
4. HAVING clause
5. SELECT clause
6. ORDER BY clause

so I was expecting the updated results to be constrained to the selected 175 records, but apparently it goes over the entire table and the result is 4.354.665 rows affected.

Is the order of operations different in a UPDATE statement, or I should redesign my query?

4

1 回答 1

3

FROM如果您希望任何应用的过滤器起作用,您需要在子句中直接引用要更新的表。就像是:

update d1 --Or d2?
set amount = (
    CASE WHEN id = d1.netID /*?*/ THEN round((d1.amount + d2.amount )/1.18, 2)
         WHEN id = d1.vatID /*?*/ THEN round(((d1.amount + d2.amount )/1.18) * 0.18, 2)
    END
    )
from
   transaction_details d1 join transaction_details d2 on d1.id = d2.netID
where
    1 = 1
  -- multiple conditions

我不确定从哪里netIDvatID实际上是从哪里来的,因为你没有在你的 nested 中显示它们SELECT,而且我猜测要更新的表是别名表d1而不是d2. 您可能可以根据上述内容进行调整以达到您的实际要求。

于 2013-06-28T08:08:50.973 回答