简体   繁体   中英

How to Create Stored procedure in DB2

Can you please help me to create a below Oracle procedure in DB2? Same table name with columns are available in DB2 also but below script is not working

CREATE OR REPLACE PROCEDURE sample_proc (ACCT_NO in CHAR,p_cursor out SYS_REFCURSOR)
is
BEGIN
 OPEN p_cursor FOR
select sampl1,sample2,sample3
from
table_test b
where
rec_id='A'
and sample3=ACCT_NO ;
END;

If you want a return better use function here are some example to get collection

CREATE TABLE table_test
(
   sample1   VARCHAR2 (1000),
   sample2   VARCHAR2 (1000),
   sample3   VARCHAR2 (1000)
);

insert into table_test ( sample1,sample2 ,sample3)
values     ('daftest1','dsdtest1','sstsest3');  
insert into table_test ( sample1,sample2 ,sample3)
values     ('FAStest1','fstest1','sstsest3');   
insert into table_test ( sample1,sample2 ,sample3)
values     ('sdtest1','asdtest1','fstest3');   
insert into table_test ( sample1,sample2 ,sample3)
values     ('test2','test2','test123');

CREATE OR REPLACE TYPE TEST_REC                                                              
AS OBJECT (
   sample1 VARCHAR2(1000)
  ,sample2 VARCHAR2(1000)
  ,sample3 VARCHAR2(1000)
);

CREATE OR REPLACE TYPE TEST_REPORT_TABLE                                                              
AS TABLE OF TEST_REC;

CREATE OR REPLACE FUNCTION testing (p_acct_no IN varchar2)
RETURN test_report_table
IS
 v_rec test_rec;
 v_test_report_table test_report_table := test_report_table();
BEGIN

FOR i IN (SELECT sample1,sample2,sample3
FROM table_test b
--where rec_id='A'
where sample3=p_acct_no)
LOOP
      v_rec:=test_rec(NULL,NULL,NULL);
dbms_output.put_line(i.sample1);

      v_rec.sample1:=i.sample1;
      v_rec.sample2:=i.sample2;
      v_rec.sample3:=i.sample3;
      v_test_report_table.EXTEND;
      v_test_report_table(v_test_report_table.COUNT) :=v_rec;


END LOOP;


RETURN v_test_report_table;




END;

    select * from table(testing(p_acct_no=>'sstsest3'))

在此处输入图片说明

Or better use bulk collect if you don't need to add rows dynamically

CREATE OR REPLACE FUNCTION JSTRAUTI.testing (p_acct_no IN varchar2)
RETURN test_report_table
IS
 v_test_report_table test_report_table := test_report_table();


BEGIN

 SELECT test_rec(sample1,sample2,sample3)
 bulk collect into v_test_report_table
FROM table_test b
--where rec_id='A'
where sample3=p_acct_no;

RETURN v_test_report_table;

END;

result the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM