Oracle動態SQL

來源:互聯網
上載者:User

動態SQL文法

只有在運行時候Oracle才能夠檢測它的格式是否正確

INTO和USING子句是可選的

如果SQL語句是一個查詢語句的話,我們可以使用INTO子句

INTO語句用於接收SELECT語句選擇的記錄值,可以是一個變數序列,也可以是一個記錄型的變數也就是record型的變數

這個變數序列的順序對應於查詢結果集中的記錄的值的順序

如果有參數需要動態確定,我們可以使用USING子句

動態建立表

樣本

  1. --動態SQL語句   
  2. begin   
  3.   execute immediate 'create table bonus (id number,ant number)';  
  4. end;  
  5.     
  6. --動態查詢使用者的電話   
  7.  declare  
  8.  sql_stmt varchar2(200); --儲存查詢語句   
  9.  emp_id number(10):='&emp_id';  
  10.  emp_rec employees%rowtype;  
  11.    
  12.  begin  
  13.     sql_stmt:='select * from employees where id=:id'  ;  
  14.     execute immediate sql_stmt into emp_rec using emp_id;  
  15.     dbms_output.put_line(emp_rec.phone);  
  16.    
  17.  end;
  18. ">--動態插入   
  19.  declare   
  20.      sql_stmt varchar(200);  
  21.      emp_id number(10):='&emp_id';  
  22.      emp_rec employees%rowtype;  
  23.  begin  
  24.    sql_stmt:='insert into employees (id) values(:id)';  
  25.    execute immediate sql_stmt using emp_id;  
  26.       
  27.  end;

execute immediate語句只能執行返回一行或者沒有返回,如果要編寫返回多行的sql語句要使用REF動態資料指標

樣本:

  1. --動態SQL,動態資料指標   
  2.  declare  
  3.     e_id number(10);  
  4.     e_name varchar2(50);  
  5.     s_salary number(8);  
  6.     type c_type is ref cursor;  
  7.     cur c_type;  
  8.     p_salaty number:='&p_id';  
  9.  begin  
  10.    open cur for   
  11.    'select e.id,e.name,s.salaryvalue from employees e,salary s  
  12.    where e.id=s.employeeid and s.salaryvalue>:sal order by id asc'  
  13.    using p_salry;  
  14.    dbms_output.put_line('薪水大於'||p_salary||'的員工有:');  
  15.    loop   
  16.      fetch cur into e_id, e_name,s_salary;  
  17.      exit when cur%notfound;  
  18.      dbms_output.put_line('編號:'||e_id||'姓名:'||e.name||'薪水'||s_salary);  
  19.      end loop;  
  20.      close cur;  
  21.  end;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.