简体   繁体   中英

Update using subquery in plsql block

If comm is null, I need to update the comm value to salary , which is 1100 , but it is not getting updated.

My data is:

sal        comm    
9000    800
2975    800
3000    800
1100    
3000    800

My code is:

declare
  cursor c3 is select sal,comm,ename from emp where deptno=20
  for update of comm;
begin
  for c in c3
  loop
    if c.comm is null
    then
      update emp set comm=(select c.sal from emp e where e.comm=c.comm )
      where current of c3;
    end if;
  end loop;
end;

Please give me opinion on this.

This line:

update emp set comm=(select c.sal from emp e where e.comm=c.comm )

... will not work. You know c.comm is null, so you're trying to find a record on emp with a matching value, and you can't use an equality test for null . This also won't work if there is more than one record where comm is null - in that case, which of the possible sal values would it use?

You don't need to query emp again at all; the select is pointless, even if it worked, since you can get the data from the row you're updating:

update emp set comm = sal
where current of c3;

You could also remove the if test by changing your cursor to only look for null values:

cursor c3 is select sal,comm,ename
  from emp
  where deptno=20
  and comm is null
  for update of comm;

But as other answers have already pointed out, you don't need to do this in PL/SQL at all, a simple SQL update would suffice.

The following should work:

update Employee
set com = sal
where com is null

这是一个简单的更新声明。

UPDATE YourTable SET comm = sal WHERE comm IS NULL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM