DB2---创建返回结果集的函数
在数据验证中,经常遇到需返回结果集的操作,故整理一个返回结果集的DB2函数,便于后期查阅
1、准备测试表
/*创建测试表:设置结果集的属性为表字段*/ CREATE TABLE Test_EXWASTE_EXC ( Test_Time TIMESTAMP ,-- Test_STATION CHARACTER(6),-- Test_Three CHARACTER(2) ,-- Test_Four varchar(3) ,-- Test_Five varchar(1) ,-- Test_MODIFY varchar(1) -- )
2、创建返回结果集的函数
/*函数的作用:refpk中以‘,’分隔的信息插入到测试表,并返回结果集*/ --/ create FUNCTION Test_Func_GetInfo(REFPK VARCHAR(500)) --REFPK为传入的参数 returns --返回值的类型为table TABLE(Out_Time TIMESTAMP, Out_Station character(6), Out_Three character(2), Out_Four SMALLINT, Out_Five smallint, Out_Modify character(1)) LANGUAGE SQL MODIFIES SQL DATA --MODIFIES SQL DATA 表示函数中有ddl操作 begin atomic DECLARE Out_Time TIMESTAMP; DECLARE Out_Station character(6); DECLARE Out_Three character(2); DECLARE Out_Four SMALLINT; DECLARE Out_Five smallint; DECLARE Out_Modify character(1); DECLARE I_INDEX INT;-- DECLARE I_Length INT; DECLARE I_Locate INT; DECLARE V_Char character(1); DECLARE I_Switch INT; DECLARE I_Return INT; DECLARE V_Refpk varchar(500); set I_Return=0; set I_INDEX=1; set I_Length=0; set I_Locate=1; set I_Switch=0; set V_Refpk=refpk||','; set I_Length=length(V_Refpk); set I_Return=1; while I_INDEX<=I_Length do --将','分隔的信息取出来 set V_Char=substr(V_Refpk,I_INDEX,1); if V_Char=',' then set I_Switch=I_Switch+1; if I_Switch=1 then set Out_Time=timestamp(substr(V_Refpk,I_Locate,I_INDEX-I_Locate)); elseif I_Switch=2 then set Out_Station=substr(V_Refpk,I_Locate,I_INDEX-I_Locate); elseif I_Switch=3 then set Out_Three=substr(V_Refpk,I_Locate,I_INDEX-I_Locate); elseif I_Switch=4 then set Out_Four=substr(V_Refpk,I_Locate,I_INDEX-I_Locate); elseif I_Switch=5 then set Out_Five=substr(V_Refpk,I_Locate,I_INDEX-I_Locate); else set Out_Modify=substr(V_Refpk,I_Locate,I_INDEX-I_Locate); end if; set I_Locate=I_INDEX+1; end if; set I_INDEX=I_INDEX+1; end while; insert into Test_EXWASTE_EXC values(Out_Time,Out_Station,Out_Three,Out_Four,Out_Five,Out_Modify); return select * from Test_EXWASTE_EXC ; end /
3、函数的调用
由于函数的返回值为table,故我们操作此函数像操作表一样
select T.OUT_TIME from table(Test_Func_GetInfo('2019-06-10 07:30:40,020801,28,154,0,1')) T where T.OUT_TIME=timestamp'2019-06-10 07:30:40' --注意T的字段是函数中定义的字段,与Test_Exwaste_exc无关
4、关键字MODIFIES SQL DATA删掉,报-374错误
https://www.cnblogs.com/handhead/
莫问收获,但问耕耘