1. 程式人生 > >第四章 PL/SQL塊 動態查詢語句和異常處理 練習題答案

第四章 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;