拆分两个分号分隔参数

时间:2014-05-08 06:20:09

标签: sql oracle plsql

如何从PL / SQL中的字符串中获取两个值,如下所示:

DECLARE
    context VARCHAR2(50) := 'param_a=Value1;param_b=Value2,Value3;';
    paramA VARCHAR(50);
    paramB VARCHAR(50);
BEGIN
    paramA = ... -- expected value: Value1
    paramB = ... -- expected value: Value2,Value3
    dbms_output.put_line(context);
END;

3 个答案:

答案 0 :(得分:1)

您可以使用以下内容:

  DECLARE
          context VARCHAR2(50) := 'param_a=Value1;param_b=Value2,Value3;';
          paramA VARCHAR(50);
          paramB VARCHAR(50);
 BEGIN
    paramA :=  SUBSTR('param_a=Value1;param_b=Value2,Value3;',instr('param_a=Value1;param_b=Value2,Value3;','=',1,1)+1,instr('param_a=Value1;param_b=Value2,Value3;',';',1,1)-instr('param_a=Value1;param_b=Value2,Value3;','=',1,1)-1);
    paramB := SUBSTR('param_a=Value1;param_b=Value2,Value3;',instr('param_a=Value1;param_b=Value2,Value3;','=',1,2)+1,instr('param_a=Value1;param_b=Value2,Value3;',';',1,2)-instr('param_a=Value1;param_b=Value2,Value3;','=',1,2)-1);

    dbms_output.put_line(paramA);
    dbms_output.put_line(paramb);

  END;

希望它有助于

Vishad

答案 1 :(得分:0)

DECLARE
  type TStrings IS TABLE OF VARCHAR2(4000);
  ltParams TStrings;
  ltParamsValue TStrings;

  function split(ivStr varchar2, ivDelim varchar2 := ',') return TStrings 
  IS
    ltStrings TStrings;
    lvStr varchar2(4000);
    i number;
  BEGIN
    lvStr := ivStr;
    ltStrings := TStrings();
    loop
      i := instr(lvStr, ivDelim);
      i := case when i = 0 and lvStr is not null then length(lvStr) else i end;
      exit when i = 0 or lvStr is null;
      ltStrings.extend(1);
      ltStrings(ltStrings.count) := rtrim(substr(lvStr, 1, i), ivDelim);
      lvStr := substr(lvStr, i + 1);
    end loop;
    RETURN ltStrings;
  END;

BEGIN
  ltParams := split('param_a=Value1;param_b=Value2,Value3;', ';');
  FOR idx IN ltParams.first .. ltParams.last LOOP
    ltParamsValue := split(ltParams(idx), '=');
    dbms_output.put_line(ltParamsValue(2));
  END LOOP;
end;

答案 2 :(得分:0)

Hi Better way to do this kind of separation is by using REGEX(Regular Expressions). 
PLease try this code it may help plus it will reduce the coding length too.

SET serveroutput ON;
DECLARE
  context VARCHAR2(50) := 'param_a=Value1;param_b=Value2,Value3;';
  paramA  VARCHAR(50);
  paramB  VARCHAR(50);
BEGIN
  FOR rec IN
  (SELECT regexp_substr(context,'[^;"]+', 1, level) AS AV_TEST
  FROM dual
    CONNECT BY regexp_substr(context,'[^;"]+', 1, level) IS NOT NULL
  )
  LOOP
    dbms_output.put_line(rec.av_test);
  END LOOP;
END;