我正在使用Cursor For循环更新loop.call_soon_threadsafe(event.set)
(与emp表相同)
emp3
执行PL / SQL块时,它会询问作业,
我给DECLARE
CURSOR incr_cur IS SELECT * FROM emp3 FOR UPDATE OF sal;
v_job emp3.job%TYPE := '&ENTER_Job';
v_cnt INTEGER := 0;
BEGIN
FOR r_l IN incr_cur LOOP
IF v_job IN (r_l.job) THEN
UPDATE emp3 SET sal = sal + 100 WHERE CURRENT OF incr_cur;
END IF;
END LOOP;
FOR r_l IN incr_cur LOOP
IF v_job IN (r_l.job) THEN
v_cnt := v_cnt + 1;
DBMS_OUTPUT.PUT_LINE('The Salary of ' || r_l.ename || ' is Incremented by 100 and the Updated Salary is: $' || r_l.sal);
END IF;
END LOOP;
DBMS_OUTPUT.PUT_LINE('The Salary of '|| v_cnt ||' Employees are Updated');
END;
,然后MANAGER
的员工的工资增加100。
MANAGER
表有5个JOB类别emp3
,CLERK
,MANAGER
,ANALYST
和SALESMAN
。
然后如何显示消息未列出作业,因此无法更新。,如果用户输入了PRESIDENT
表中不存在的作业。
我曾尝试过异常处理,但无法让它工作。
答案 0 :(得分:1)
这里有一个选择:检查这样的工作是否存在;如果没有,查询将返回您可以处理的NO_DATA_FOUND
,并使用适当的消息引发异常。否则,请继续UPDATE
。
SQL> declare
2 l_job emp.job%type;
3 begin
4 begin
5 select job
6 into l_job
7 from emp
8 where job = '&ENTER_Job'
9 and rownum = 1;
10 exception
11 when no_data_found then
12 raise_application_error(-20000, 'That job does not exist');
13 end;
14
15 -- Job exists, so - go on with the update
16 end;
17 /
Enter value for enter_job: MANAGER
PL/SQL procedure successfully completed.
SQL> /
Enter value for enter_job: DEVELOPER
declare
*
ERROR at line 1:
ORA-20000: That job does not exist
ORA-06512: at line 12
SQL>
P.S。忘记提及:我更喜欢通过存储过程(接受作业名称作为参数)而不是匿名PL / SQL块来完成这样的工作。
答案 1 :(得分:1)
不需要单独的步骤。只是尝试更新,如果没有更新行,请说明。如果您希望它成为例外,请使用raise_application_error
举一个。
假设这是一个学习练习,这就是为什么你不想只做一个普通的update
,你可能会做这样的事情:
declare
k_job constant emp3.job%type := '&JOB';
cursor employees_cur is
select * from emp3
where job = k_job
for update of sal;
v_update_count integer := 0;
v_payroll_increase integer := 0;
begin
for r in employees_cur loop
update emp3 set sal = sal + 100 where current of employees_cur;
dbms_output.put_line('Salary for ' || r.ename || ' is incremented by $100 from $' || r.sal || ' to $' || (r.sal +100));
v_update_count := v_update_count + 1;
v_payroll_increase := v_payroll_increase + 100;
end loop;
if v_update_count = 0 then
dbms_output.put_line('No staff are currently employed as ' || k_job ||'. Payroll is unchanged.');
else
dbms_output.put_line('Updated salary of '|| v_update_count ||' employee' || case when v_update_count <> 1 then 's' end||'.');
dbms_output.put_line('Payroll increased by $'||v_payroll_increase||'.');
end if;
end;
/
Enter value for job: SALESMAN
Salary for ALLEN is incremented by $100 from $1600 to $1700
Salary for WARD is incremented by $100 from $1250 to $1350
Salary for MARTIN is incremented by $100 from $1250 to $1350
Salary for TURNER is incremented by $100 from $1500 to $1600
Updated salary of 4 employees.
Payroll increased by $400.
PL/SQL procedure successfully completed.
对于不存在的工作,你得到这个:
Enter value for job: ASTRONAUT
No staff are currently employed as ASTRONAUT. Payroll is unchanged.
(在此示例中,v_payroll_increase
始终为v_update_count
的100倍,但如果您希望按部门等提高10%或增加不同,则可能更有用。)