第四章 PL/SQL块 动态查询语句和异常处理 练习题答案

动态执行SQL语句:
1、用PLSQL给emp添加dname列,然后更新这个列的数据;
异常和动态执行SQL部分:
declare
sql_stmt1 varchar2(200); –动态SQL语句
sql_stmt2 varchar2(200);
begin
sql_stmt1:= –给emp添加dname列
‘alter table emp add (dname varchar2(20))’;

sql_stmt2:= –更新这个列的数据
‘update emp sat dname=(select dname from dept where emp.deptno=dept.deptno)’;
execute immediate sql_stmt1;
execute immediate sql_stmt2;
end;

=========================================================================

2、输入某个学生名字,查询该学生的信息,如果该学生不存在,
则引发异常,输出信息,该学生不存在
declare
name t_students.sname%type := ‘&name’;
students t_students%rowtype;
begin
select sno,sname,sage,ssex into students from t_students where sname= name;
dbms_output.put_line
(‘学号是’||students.sno||’,姓名是’||students.sname||’,性别是’||students.ssex||’,年龄’||students.sage);
exception
when no_data_found then
dbms_output.put_line(‘该学生不存在!’);
end;

==========================================================================

3、 使用一个PL/SQL程序实现:
(1)查询员工表中工资大于1500的员工信息,
关联部门表获得部门名称,以该查询的结果创建视图,
视图名称为empdeptview,通过查询该视图进行temp表的创建;
(2)查询temp表,empno=7698,获得该员工的工资信息,
如果工资是大于2000,则视为异常,
并输出异常内容,’工资过高’,否则为正常。

declare
p_empno emp.empno%type:=’&empno’;
p_sal emp.sal%type;
myexp exception;
begin
execute immediate ‘drop view empdeptview’;
execute immediate ‘drop table temp’;
execute immediate ‘create view empdeptview as
select e.*,d.dname from emp e
left join dept d on e.deptno=d.deptno
where e.sal>1500
with read only’;
execute immediate ‘create table temp as
select * from empdeptview’;
EXECUTE IMMEDIATE ‘select sal from temp where empno=:empno’ into p_sal USING p_empno;
–引发异常
if p_sal>2000 then
RAISE myexp;
else
dbms_output.put_line(p_empno||’的工资是’||p_sal);
end if;

  --异常处理
  Exception
  when myexp then dbms_output.put_line('工资过高');
  when others then dbms_output.put_line('未知异常');

end;

再创建一个PL/sql块

(3) 要求使用RETURNING
查询temp表中,empno =7698获取该员工是否有津贴,
如果有的话,输出’有津贴,金额为||补助金额’
如果没有的话,查询emp表,将该员工的津贴金
额修改为200,并输出’没有津贴,工资为||工资||,
修改后的津贴金额为200’。
declare
empno emp.empno%type:=7698;
sql_temp varchar(200);
sal emp.sal%type;
comm emp.comm%type;
sname emp.ename%type;
begin
select comm into comm from emp e where e.empno=7698;
if comm is not null
then
dbms_output.put_line(‘有津贴,金额为’||comm);
else
sql_temp:=’update emp set comm =200 where empno=:1 returning sal,ename into :sal,:sname’;
execute immediate sql_temp using empno returning into sal,sname;
dbms_output.put_line(sname||’没有津贴,工资为’||sal||’,修改后的津贴金额为200’);
end if;
end;

猜你喜欢

转载自blog.csdn.net/weixin_42800008/article/details/81282618
今日推荐