How to a filter on the result on a stored procedure in DB2

岁酱吖の 提交于 2019-12-24 19:11:47

问题


I have a stored procedure in DB2 which returns a bunch of columns. I need to apply a 'WHERE' condition or do a sorting on one of the columns it returns. I don't want to touch the stored procedure and do this filtering/sorting when calling the stored procedure, something like below

select * from 'call SP1()' as T where T.column1 > 10

Is this possible in DB2?


回答1:


Here is a deliberately artificial example of a pipelined UDF that filters the result-set of an SQLPL procedure.

In real world coding, most programmers will avoid filtering outside of stored-procedures, simply because it is easier and better performing, and more natural to filter at the earliest possible opportunity.

Tested on Db2-LUW v11.1.3.3 and 11.1.2.2 with DB2_COMPATIBILITY_MODE=ORA (or at least Bit-17 set to 1 as in 0x10000 , acknowledgement to P.Vernon for this clarification):

--#SET TERMINATOR @

create or replace procedure alltabs
dynamic result sets 1
language sql
specific alltabs
begin
  declare v_cur cursor with return to caller for 
      select tabschema,tabname,type  from syscat.tables ;
  open v_cur;
end@


create or replace function allstatviews()
returns table (stat_view_name varchar(80))
begin
  declare v_rs result_set_locator varying;
  declare v_tabschema varchar(128);
  declare v_tabname   varchar(128);
  declare v_type      char(1);
  declare sqlstate char(5) default '00000';
  call alltabs;
  associate result set locator (v_rs) with procedure alltabs;
  allocate v_rscur cursor for result set v_rs;
  fetch from v_rscur into v_tabschema, v_tabname, v_type;
  while ( sqlstate = '00000') do
      if v_type='V' and v_tabschema='SYSSTAT'
      then
          pipe(cast(rtrim(v_tabschema)||'.'||rtrim( v_tabname) as varchar(80)));
      end if;
      fetch from v_rscur into v_tabschema, v_tabname, v_type;
  end while;
  return;
end@

select * from table(allstatviews())
@


来源:https://stackoverflow.com/questions/49923708/how-to-a-filter-on-the-result-on-a-stored-procedure-in-db2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!