Why can't I use SELECT … FOR UPDATE with aggregate functions?

后端 未结 3 952
臣服心动
臣服心动 2021-01-01 22:23

I have an application where I find a sum() of a database column for a set of records and later use that sum in a separate query, similar to the following (made up tables, bu

3条回答
  •  清歌不尽
    2021-01-01 23:10

    You might try something like:

    <>
    declare
      material_id materials.material_id%Type;
      cost        materials.cost%Type;
      total_cost  materials.cost%Type;
    begin
      select material_id,
             cost,
             sum(cost) over () total_cost
      into   local.material_id,
             local.cost,
             local.total_cost 
      from   materials
      where  material_id between 1 and 3
      for update of cost;
    
      ...
    
    end local;
    

    The first row gives you the total cost, but it selects all the rows and in theory they could be locked.

    I don't know if this is allowed, mind you -- be interesting to hear whether it is.

提交回复
热议问题