Split function in oracle to comma separated values with automatic sequence

后端 未结 8 984
遇见更好的自我
遇见更好的自我 2020-11-28 09:37

Need Split function which will take two parameters, string to split and delimiter to split the string and return a table with columns Id and Data.And how to call Split funct

8条回答
  •  隐瞒了意图╮
    2020-11-28 10:19

    This function returns the nth part of input string MYSTRING. Second input parameter is separator ie., SEPARATOR_OF_SUBSTR and the third parameter is Nth Part which is required.

    Note: MYSTRING should end with the separator.

    create or replace FUNCTION PK_GET_NTH_PART(MYSTRING VARCHAR2,SEPARATOR_OF_SUBSTR VARCHAR2,NTH_PART NUMBER)
    RETURN VARCHAR2
    IS
    NTH_SUBSTR VARCHAR2(500);
    POS1 NUMBER(4);
    POS2 NUMBER(4);
    BEGIN
    IF NTH_PART=1 THEN
    SELECT REGEXP_INSTR(MYSTRING,SEPARATOR_OF_SUBSTR, 1, 1)  INTO POS1 FROM DUAL; 
    SELECT SUBSTR(MYSTRING,0,POS1-1) INTO NTH_SUBSTR FROM DUAL;
    ELSE
    SELECT REGEXP_INSTR(MYSTRING,SEPARATOR_OF_SUBSTR, 1, NTH_PART-1) INTO  POS1 FROM DUAL; 
    SELECT REGEXP_INSTR(MYSTRING,SEPARATOR_OF_SUBSTR, 1, NTH_PART)  INTO POS2 FROM DUAL; 
    SELECT SUBSTR(MYSTRING,POS1+1,(POS2-POS1-1)) INTO NTH_SUBSTR FROM DUAL;
    END IF;
    RETURN NTH_SUBSTR;
    END;
    

    Hope this helps some body, you can use this function like this in a loop to get all the values separated:

    SELECT REGEXP_COUNT(MYSTRING, '~', 1, 'i') INTO NO_OF_RECORDS FROM DUAL;
    WHILE NO_OF_RECORDS>0
    LOOP
        PK_RECORD    :=PK_GET_NTH_PART(MYSTRING,'~',NO_OF_RECORDS);
        -- do some thing
        NO_OF_RECORDS  :=NO_OF_RECORDS-1;
    END LOOP;
    

    Here NO_OF_RECORDS,PK_RECORD are temp variables.

    Hope this helps.

提交回复
热议问题