Thursday, October 26, 2017

Get values from Comma/CSV/TAB delimiter string - Oracle 11g

CREATE OR REPLACE FUNCTION get_field (p_text       IN VARCHAR2,
                    p_position   IN NUMBER,
                    p_sep        IN VARCHAR2)  RETURN VARCHAR2
IS

   l_sep         VARCHAR2 (1);
   l_output      VARCHAR2 (240);

BEGIN

   IF UPPER (p_sep) = 'TAB'
   THEN
      l_sep := CHR (9);
   ELSIF UPPER (p_sep) = 'CSV'
   THEN
      l_sep := ',';
   END IF;

   l_output := TRIM ((REPLACE (REPLACE (SUBSTR(rtrim( regexp_substr( p_text || l_sep, '.*?' || l_sep, 1, p_position ), l_sep ),1,240), CHR (10), ''), CHR (13), '')));
   RETURN (l_output);


END get_field;

Output 

TAB delimiter string


SQL> SELECT GET_FIELD('ABC CHIDAM RAM DIV ',1,'TAB') FROM DUAL;
GET_FIELD('ABCCHIDAMRAMDIV',1,
--------------------------------------------------------------------------------
ABC

SQL> SELECT GET_FIELD('ABC CHIDAM RAM DIV ',2,'TAB') FROM DUAL;
GET_FIELD('ABCCHIDAMRAMDIV',2,
--------------------------------------------------------------------------------
CHIDAM

SQL> SELECT GET_FIELD('ABC CHIDAM RAM DIV ',3,'TAB') FROM DUAL;
GET_FIELD('ABCCHIDAMRAMDIV',3,
--------------------------------------------------------------------------------
RAM

SQL> SELECT GET_FIELD('ABC CHIDAM RAM DIV ',4,'TAB') FROM DUAL;
GET_FIELD('ABCCHIDAMRAMDIV',4,
--------------------------------------------------------------------------------

SQL> SELECT GET_FIELD('ABC CHIDAM RAM DIV ',5,'TAB') FROM DUAL;
GET_FIELD('ABCCHIDAMRAMDIV',5,
--------------------------------------------------------------------------------

SQL> SELECT GET_FIELD('ABC CHIDAM RAM DIV ',6,'TAB') FROM DUAL;
GET_FIELD('ABCCHIDAMRAMDIV',6,
--------------------------------------------------------------------------------
DIV

CSV/Comma fields


SQL> SELECT GET_FIELD('ABC,CHIDAM,RAM,,,DIV',1,'CSV') FROM DUAL;
GET_FIELD('ABC,CHIDAM,RAM,,,DI
--------------------------------------------------------------------------------
ABC

SQL> SELECT GET_FIELD('ABC,CHIDAM,RAM,,,DIV',2,'CSV') FROM DUAL;
GET_FIELD('ABC,CHIDAM,RAM,,,DI
--------------------------------------------------------------------------------
CHIDAM

SQL> SELECT GET_FIELD('ABC,CHIDAM,RAM,,,DIV',5,'CSV') FROM DUAL;
GET_FIELD('ABC,CHIDAM,RAM,,,DI
--------------------------------------------------------------------------------

SQL> SELECT GET_FIELD('ABC,CHIDAM,RAM,,,DIV',6,'CSV') FROM DUAL;
GET_FIELD('ABC,CHIDAM,RAM,,,DI
--------------------------------------------------------------------------------
DIV

No comments:

Post a Comment

Price List Query for Item

 SELECT qph.list_header_id,        qph.name,        qph.description,        qphh.start_date_active,        qphh.currency_code,        q...