Oracle自定義函式實現動態引數複製表(使用了自定義type以及pipelined)
阿新 • • 發佈:2019-01-27
(作者:陳玓玏)
之前試了一下,想用自定義函式及遊標實現動態傳入引數,確實可以,但是輸出結果總是不能成表格。
查了一圈,Oracle自定義函式好像是不能直接在SQL語句中寫create as select和insert into這些功能的,但是後來的版本中提供了一個叫pipelined 的功能,但是需要自定義類。下面把我跑通了的過程寫出來。
--返回多行值且是表格的形式,但是在執行時需要用create as或insert into才能真正寫入表格 --type必須按照生成順序從後往前刪除,否則會報錯,所以最後使用到type的表或型別要最先刪除 drop table risk_temp.cdl_tb1; drop function fun1; drop type table_type1; drop type row_type1; --先建立表結構 create table risk_temp.cdl_tb1(col1 number, col2 varchar2(10)); --下面這些往建立的表裡插入的資料的程式碼可以不要的 insert into risk_temp.cdl_tb1(col1, col2) values(100,'aaa'); insert into risk_temp.cdl_tb1(col1, col2) values(200,'bbb'); insert into risk_temp.cdl_tb1(col1, col2) values(200,'ccc'); select * from risk_temp.cdl_tb1; --建立型別及表型別 create type row_type1 as object(col1 number, col2 varchar2(10)); create type table_type1 as table of row_type1; --建立函式以表格形式逐行輸出,表格形式就是之前定義的表型別 create or replace function fun1(name VARCHAR2) return table_type1 pipelined as tempvar row_type1; begin for myrow in (select col1,col2 from tableName where id=name) loop tempvar := row_type1(myrow.col1, myrow.col2); pipe row (tempvar); end loop; return; end; --執行。如果這裡不insert into或者create as,那麼之前建立的表不會有任何結果,只是顯示的結果是表形式的,但實際並沒有插 入到表中 insert into risk_temp.cdl_tb1 select * from table(fun1(name=>1445903));
關於pipelined和type的具體的更高階的用法,以後再探索吧~