動態SQL文法
只有在運行時候Oracle才能夠檢測它的格式是否正確
INTO和USING子句是可選的
如果SQL語句是一個查詢語句的話,我們可以使用INTO子句
INTO語句用於接收SELECT語句選擇的記錄值,可以是一個變數序列,也可以是一個記錄型的變數也就是record型的變數
這個變數序列的順序對應於查詢結果集中的記錄的值的順序
如果有參數需要動態確定,我們可以使用USING子句
動態建立表
樣本
- --動態SQL語句
- begin
- execute immediate 'create table bonus (id number,ant number)';
- end;
-
- --動態查詢使用者的電話
- declare
- sql_stmt varchar2(200); --儲存查詢語句
- emp_id number(10):='&emp_id';
- emp_rec employees%rowtype;
-
- begin
- sql_stmt:='select * from employees where id=:id' ;
- execute immediate sql_stmt into emp_rec using emp_id;
- dbms_output.put_line(emp_rec.phone);
-
- end;
- ">--動態插入
- declare
- sql_stmt varchar(200);
- emp_id number(10):='&emp_id';
- emp_rec employees%rowtype;
- begin
- sql_stmt:='insert into employees (id) values(:id)';
- execute immediate sql_stmt using emp_id;
-
- end;
execute immediate語句只能執行返回一行或者沒有返回,如果要編寫返回多行的sql語句要使用REF動態資料指標
樣本:
- --動態SQL,動態資料指標
- declare
- e_id number(10);
- e_name varchar2(50);
- s_salary number(8);
- type c_type is ref cursor;
- cur c_type;
- p_salaty number:='&p_id';
- begin
- open cur for
- 'select e.id,e.name,s.salaryvalue from employees e,salary s
- where e.id=s.employeeid and s.salaryvalue>:sal order by id asc'
- using p_salry;
- dbms_output.put_line('薪水大於'||p_salary||'的員工有:');
- loop
- fetch cur into e_id, e_name,s_salary;
- exit when cur%notfound;
- dbms_output.put_line('編號:'||e_id||'姓名:'||e.name||'薪水'||s_salary);
- end loop;
- close cur;
- end;