1.用遊標取資料然後處理(Bulk collect 用法)
CREATE OR REPLACE TYPE A AS OBJECT (
id NUMBER(9),
name VARCHAR2 (20)
)
CREATE OR REPLACE TYPE atypelist AS TABLE OF A;
/*定義type類型 A.
DECLARE
TYPE cur_type IS REF CURSOR;
TYPE tab_type IS TABLE OF A;
c_find_data cur_type;
v_tab tab_type;
BEGIN
OPEN c_find_data FOR 'SELECT * FROM A';
LOOP
FETCH c_find_data BULK COLLECT INTO v_tab LIMIT 10000; ---從遊標中每取10000行存入bulk collect 的集合對象中
EXIT WHEN v_tab.count=0;
FOR i in 1..v_tab.count LOOP
--do you logic
END LOOP;
END LOOP;
CLOSE c_find_data;
END;
例子:
declare
type cur_type is ref cursor ;
type tb_type is table of a%rowtype;
cur_v cur_type;
tb_v tb_type;
begin
open cur_v for 'select * from a where rownum < 1000';
fetch cur_v bulk collect
into tb_v ;
forall i in 1 .. tb_v.count
insert into curv values tb_v(i);
close cur_v;
end;
2.將一個表的欄位更新另一個表的欄位
2.1 update m set m.money= (select n.money from n where n.id = m.id );
2.2 update m set m.money=n.money from n,m where m.id=n.id
3.求: 一個select 語句
現兩個表:table1:
僱員ID 僱員姓名
empid empName
1 emp1
2 emp2
3 emp2
4 emp4
5 emp5
table2:
工程ID 角色1 角色2 角色3
gcid js1 js2 js3
1 1 2 3
2 2 3 4
3 3 4 5
其中:表2中的角色1/2/3對應表1中的僱員ID.
要求:寫一select語句,將table2中的角色1\2\3顯示為僱員姓名.
SQL:
SELECT gcid,
max(CASE WHEN js1 = empid THEN empname END) WHEN1,
max(CASE WHEN js2 = empid THEN empname END) WHEN2,
max(CASE WHEN js3 = empid THEN empname END) WHEN3
FROM mm,nn
GROUP BY gcid;
4.一維表的例子:
declare
i number;
type table1 is table of varchar2(9) index by binary_integer; */定義定義一維的type 類型
v_tab table1 ; */定義一維表的變數
cursor c is select salesman_name from sales_range where rownum<10;
str sales_range.salesman_name%type;
begin
open c;
for i in 1..9 loop
fetch c into str;
v_tab(i):=str;
insert into d values(v_tab(i));
end loop;
end;