不允许更新此查询表达式(游标)

时间:2018-07-12 07:36:13

标签: oracle plsql cursor

我正在查询下面运行

Select location, sum(units) as Units
from
( Select a.from_loc as location, sum(units) as units
from emp a, dept b
where a.id=b.id
Union all
Select a.to_loc as location, sum(units) as units
feom emp a, dept b
where a.id=b.id)
group by location;

以上查询以以下格式提供了我的数据。

Location | sum(Units)
--------------------
100      |  350
200      |  450

现在我需要用上述查询给定的单位更新另一个表类。 班级将“位置”作为主键列,并将“单位”列也包含在内。

我试图创建一个游标,但是它抛出错误,因为无法使用更新

这是光标代码的片段

Declare
V_location number(20);
V_units (20),
Cursor c1 is
Select location, sum(units) as Units
from
 ( Select a.from_loc as location, sum(units) as units
   from emp a, dept b
    where a.id=b.id
    Union all
    Select a.to_loc as location, sum(units) as units
     from emp a, dept b
     where a.id=b.id)
      group by location -----above select query
 for update;
Begin
 Open c1;
 Loop
 Fetch c1 into v_location, v_units;
 Exit when c1%notfound;

 Update class set units=v_units
 where location=v_location;
  End loop;
  Close c1;
 End;

它的抛出不允许更新此查询表达式 有人可以让我知道我在这里做错了什么。或其他一些方法来更新类表

1 个答案:

答案 0 :(得分:0)

这有好处吗?

  • 我认为FOR UPDATE子句会引起问题
  • 我删除了整个DECLARE部分,并在游标SELECT循环中使用了FOR语句,因为它易于维护(无打开,关闭,退出等)。 / li>

BEGIN
   FOR cur_r IN (  SELECT location, SUM (units) AS units
                     FROM (SELECT a.from_loc AS location, SUM (units) AS units
                             FROM emp a, dept b
                            WHERE a.id = b.id
                           UNION ALL
                           SELECT a.to_loc AS location, SUM (units) AS units
                             FROM emp a, dept b
                            WHERE a.id = b.id)
                 GROUP BY location)
   LOOP
      UPDATE class
         SET units = cur_r.units
       WHERE location = cur_r.location;
   END LOOP;
END;

[阅读评论后,编辑]

IF-THEN-ELSE将使用CASE(或DECODE)来完成;例如:

update class set
  units = case when location between 1 and 100 then cur_r.units / 10
               else cur_r.units / 20
          end
where location = cur_r.location