SQL 陳述式匯總-Bulk Collect Into及行列轉換

來源:互聯網
上載者:User

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;

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.