huawei-字符串分割,动态sql,instr,substr,循环for...loop


分割字符串insert into XX(列名) values('aaa')
CREATE OR REPLACE PROCEDURE Sp_Utl_Split(
  iStr VARCHAR2, --aaa~abc~df
  iTab VARCHAR2, -- 表名
  iCol VARCHAR2, --列名
  iSign VARCHAR2 -- ~
)
AS
  tStr VARCHAR2(3000);
  v_pos1 NUMBER(5):=1;
  v_pos2 NUMBER(5):=1;
  v_time NUMBER(5):=1;
  oSql VARCHAR2(3000);
  tStr1 VARCHAR2(300);
BEGIN
  oSql := 'TRUNCATE TABLE '||iTab;
  EXECUTE IMMEDIATE oSql;
  tStr := iSign||iStr||iSign;
  WHILE v_pos2 <> 0 LOOP
  v_pos1 := v_pos2;
  v_pos2 := INSTR(tStr , iSign, v_time + 1, 1);
  tStr1 := SUBSTR(tStr, v_pos1+1, v_pos2-v_pos1-1);
  IF tStr1 IS NOT NULL THEN
  oSql := ' insert into '||iTab||'('||iCol||') values(';
  oSql := oSql||tStr1||')';
  EXECUTE IMMEDIATE oSql;
  END IF;
  oSql := '';
  v_time := v_pos2+1;
  END LOOP;
  COMMIT;
EXCEPTION
  WHEN OTHERS THEN
  ROLLBACK;
  RETURN;
END Sp_Utl_Split;
/
CREATE OR REPLACE PROCEDURE spDelCallData
(
  sServiceID VARCHAR2, -- 组合参数 形式如: aaa,bbb,ccc .....
  usRetValue OUT INT
)AS
  TYPE serviceGroup IS TABLE OF VARCHAR2(32) INDEX BY BINARY_INTEGER;
  sServiceIDGroup serviceGroup ; --拆分数组 
  groupIndex BINARY_INTEGER:=0;--数组计数下标
  serviceIndex NUMBER(4);--分隔符下标  
  serviceTemp VARCHAR2(32);--临时转换
  strServiceId VARCHAR2(30000);--字符串
  s_split VARCHAR2(4):= ',' ;--分隔符
BEGIN
  strServiceId := sServiceID ;
  --拆分字符串
  LOOP
  IF instr(strServiceId,s_split)=0 THEN--最后一个单独处理,不再查找分隔符D
  sServiceIDGroup(groupIndex):=strServiceId ;
  EXIT;
  ELSE --非最后一个
  serviceIndex :=instr(strServiceId,s_split);
  serviceTemp :=substr(strServiceId,1,serviceIndex-1);
  sServiceIDGroup(groupIndex):=serviceTemp;
  strServiceId :=substr(strServiceId,serviceIndex+1,length(strServiceId));
  groupIndex:=groupIndex+1;
  END IF;
  END LOOP;
  --开始使用分隔好的字符=
  FOR i IN sServiceIDGroup.FIRST.. sServiceIDGroup.LAST LOOP
  serviceTemp := sServiceIDGroup(i) ;
  delete from tCallData t where t.serviceid = serviceTemp
  END LOOP;
  usRetValue := 0 ;
  commit;
EXCEPTION
  WHEN OTHERS THEN
  usRetValue := 1 ;
  RETURN;
END spDelCallData;
/

你可能感兴趣的:(数据库-存储过程,数据库-函数,数据库-动态sql)