oracle 11g 學習筆記 11_4

來源:互聯網
上載者:User
pl/sql基礎
1、pl/sql概念
pl/sql(procedural language/sql)是oracle在標準的sql語言上的擴充。pl/sql不僅允許嵌入sql語言,還可以定義變數和常量,允許使用條件陳述式和迴圈語句,允許使用例外處理各種錯誤,這樣使得它的功能變得更加強大。

.編寫一個預存程序,該過程可以向某表中添加記錄
1. 建立一個簡單表
create table mytest(name varchar2(30),passwd varchar2(30));
2. 建立預存程序
create or replace procedure sp_pro2 is 
begin
--執行部分
insert into mytest values('pangzi','m123');
end;

replace:
如何查看錯誤資訊:show error;
如何調用
1)exec 過程名(參數值1,參數值2...)
2)call 過程名(參數值1,參數值2...)
二、變數,複合類型
1、變數
1.標量(scalar)
pl/sql塊為變數賦值不同於其它程式設計語言,需要在等號前加冒號( := );

--案例--輸入員工號,顯示僱員姓名、工資、個人所得稅(稅率為0.03)declarev_name emp.ename%type;v_sal emp.sal%type;v_tax_sal number(7,2);--個人所得稅c_tax_rate number(7,2) :=0.03; --給稅率賦值begin select ename, sal into v_name, v_sal from emp where empno=&no;--計算所得稅v_tax_sal :=v_sal*c_tax_rate;--列印dbms_output.put_line('僱員姓名:'||v_name ||' 工資:'||v_sal ||' 個人所得稅:' ||v_tax_sal);end;

2。複合變數
符合變數用於存放多個值的變數,主要包括這幾種:
pl/sql 記錄
pl/sql 表
巢狀表格

i.記錄
記錄類似於進階語言中的結構體,當引用pl/sql記錄成員時,引用的規則是:記錄變數.記錄成員

--案例2--定義一個記錄類型,用來存放僱員姓名,工資,工作--eclare type emp_record_type is record(        name emp.ename%type,        salary emp.sal%type,        myJob emp.job%type);--定義一個是emp_record_type 類型的變數sp_recordsp_record emp_record_type;begin  --執行  select ename,sal,job into sp_record from emp where empno =&no;  --列印資訊  dbms_output.put_line(       '僱員姓名:' ||sp_record.name ||' 工資:'||sp_record.salary ||' 工作是:'||sp_record.myJob);end;

2.表
表類似於進階語言中的數組,但是需要注意的是在進階語言中數組的下表不能為負,而pl/sql是可以為負數的,並且表元素的下表沒有限制.

--案例3--定義一個pl/sql表類型sp_table_typedeclare type sp_table_type is table of emp.ename%typeindex by binary_integer;--表的下標是正數--定義一個sp_table 類型是sp_table_typesp_table sp_table_type;begin   select ename into sp_table(-1) from emp where empno =7788;  --輸出  dbms_output.put_line('僱員姓名:' ||sp_table(-1));end;

3.參照變數--ref cursor 遊標變數
使用遊標時,當定義遊標時不需要指定的select語句,但是當使用遊標時(open時)需要指定select語句,這樣一個遊標就與一個select語句結合了。

--執行個體4--編寫一個塊,可以輸入部門號,並顯示該部門所有員工姓名和他的工資--如果某個員工的工資低於200元,就添加100元declare--定義遊標sp_emp_cursortype sp_emp_cursor is ref cursor;--定義一個遊標變數test_cursor sp_emp_cursor;--定義變數,用於儲存員工姓名和工資v_ename emp.ename%type;v_sal emp.sal%type;--emp.sal%type 表示的是v_sal的類型和emp表的sal的類型一樣.begin --執行部分open test_cursor for select ename,sal from emp where deptno =&no;--迴圈取出loop--取出並放入變數fetch test_cursor into v_ename,v_sal;--迴圈結束條件是exit when test_cursor%notfound;--輸出dbms_output.put_line('僱員姓名:'||v_ename||'工資:'||v_sal);end loop;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.