REGEXP_SUBSTR for the list delimited by commas with null values

Hello

I have a column that stores a list of values comma-delimited. Some of these values in the list may be null. I'm having some trouble trying to extract the values using the REGEXP_SUBSTR function when null values are present. Here are two things I've tried:
SELECT
   REGEXP_SUBSTR (val, '[^,]*', 1, 1) pos1
  ,REGEXP_SUBSTR (val, '[^,]*', 1, 2) pos2
  ,REGEXP_SUBSTR (val, '[^,]*', 1, 3) pos3
  ,REGEXP_SUBSTR (val, '[^,]*', 1, 4) pos4
  ,REGEXP_SUBSTR (val, '[^,]*', 1, 5) pos5
FROM (SELECT 'AAA,BBB,,DDD,,FFF' val FROM dual);

POS P POS P P
--- - --- - -
AAA   BBB
SELECT
   REGEXP_SUBSTR (val, '[^,]+', 1, 1) pos1
  ,REGEXP_SUBSTR (val, '[^,]+', 1, 2) pos2
  ,REGEXP_SUBSTR (val, '[^,]+', 1, 3) pos3
  ,REGEXP_SUBSTR (val, '[^,]+', 1, 4) pos4
  ,REGEXP_SUBSTR (val, '[^,]+', 1, 5) pos5
FROM (SELECT 'AAA,BBB,,DDD,,FFF' val FROM dual);

POS POS POS POS P
--- --- --- --- -
AAA BBB DDD FFF
As you can see that neither calls work correctly. Anyone know how to change the regular expression pattern to handle null values? I tried various other models but could not get anyone to work in all cases.

Thank you

Martin
-----
http://www.ClariFit.com
http://www.TalkApex.com

Hi, Martin,.

That's what you want:

SELECT
   RTRIM (REGEXP_SUBSTR (val, '[^,]*,', 1, 1), ',') pos1
  ,RTRIM (REGEXP_SUBSTR (val, '[^,]*,', 1, 2), ',') pos2
  ,RTRIM (REGEXP_SUBSTR (val, '[^,]*,', 1, 3), ',') pos3
  ,RTRIM (REGEXP_SUBSTR (val, '[^,]*,', 1, 4), ',') pos4
  ,RTRIM (REGEXP_SUBSTR (val || ','
                      , '[^,]*,', 1, 5), ',') pos5
FROM (SELECT 'AAA,BBB,,DDD,,FFF' val FROM dual);

The query above works in Oracle 10 or 11, but in Oracle 11, you can also do it with only REGEXP_SUBSTR, without using RTRIM:

SELECT
   REGEXP_SUBSTR (val, '([^,]*),|$', 1, 1, NULL, 1) pos1
  ,REGEXP_SUBSTR (val, '([^,]*),|$', 1, 2, NULL, 1) pos2
  ,REGEXP_SUBSTR (val, '([^,]*),|$', 1, 3, NULL, 1) pos3
  ,REGEXP_SUBSTR (val, '([^,]*),|$', 1, 4, NULL, 1) pos4
  ,REGEXP_SUBSTR (val, '([^,]*),|$', 1, 5, NULL, 1) pos5
FROM (SELECT 'AAA,BBB,,DDD,,FFF' val FROM dual);

The problem with your first request was that he was looking for sub channels of 0 or more non-virgules. There was as a substring. consisting of 3 characters starting at position 1, he returned "AAA", as expected. Then there was an another substring, the 0 characters, starting at position 4, so it returned NULL. Then, there was a substring of 3 characters starting at position 5, so he returned 'BBB '.

The problem with your 2nd request was that he was looking for 1 or more non-virgules. 'DDD' is the 3rd this substring.

Published by: Frank Kulash, on February 16, 2012 11:36
Added Oracle 11 example

Tags: Database

Similar Questions

  • Problem using the list separated by commas with nested table element

    Hello

    I have a list separated by commas like this:
    H23004,H24005,T7231,T8231,T9231
    And want to create a function that creates a where clause clause for each element with an output like this:
    UPPER('H23004') IN (UPPER(charge))
    OR UPPER('H23005') IN (UPPER(charge))
    OR UPPER('T7231') IN (UPPER(charge))
    OR UPPER('T8231') IN (UPPER(charge))
    OR UPPER('T9231') IN (UPPER(charge))
    Here's my test function that is not working properly:
    create or replace function FNC_LIST_TO_WHERE_CLAUSE(v_list in VARCHAR2) return varchar2 is
     -- declaration of list type
     TYPE batch_type IS TABLE OF pr_stamm.charge%TYPE;
     -- variable for Batches
     v_batch batch_type := batch_type('''' || replace(v_list,',',''',''') || '''');
     return_script varchar2(1000);
    
     BEGIN
     -- loop as long as there are objects left
     FOR i IN v_batch.FIRST .. v_batch.LAST
     LOOP
       --DBMS_OUTPUT.PUT_LINE(offices(i));
       -- create where clause
       IF i = 1 THEN
         return_script := 'UPPER(' || v_batch(i) || ') IN (UPPER(charge))';
       ELSE
         return_script := return_script || ' OR UPPER(' || v_batch(i) || ') IN (UPPER(charge))';
       END IF;
     END LOOP;
    
     return (return_script);
     end;
    The out put looks like this:
    UPPER('H23004','H24005','T7231','T8231','T9231') IN (UPPER(charge))
    I don't know what I did wrong? It calculates the amount of the incorrect array element! (v_batch. Must be 5)
    v_batch. FIRST = 1
    v_batch. LAST = 1

    Kind regards

    Tobias

    Try this...

    declare
    text varchar2 (1000): = "H23004, H24005, T7231, T8231, T9231;
    v_where varchar2 (1000);
    Start
    Text: = text | «, » ;
    While instr (text, ',') <> 0
    loop
    v_where: = v_where | ' UPPER ("': substr (Text, 1, InStr(Text,',',1)-1) |") ' IN (UPPER (load)) OR ';
    text: = substr (text, instr(text,',',1) + 1);
    end loop;
    v_where: = substr (v_where, 1, length (v_where)-3);
    dbms_output.put_line (v_where);
    end;

    convert it to function...

  • Query to find the Pages and the list of permissions associated with a particular role in PS

    I want a query to find the Pages and the list of permissions associated with specific roles in PS.

    For example, if we see the role of manager accounts payable, it conatins Pages and the list of permissions.

    But, to get everything in EXCEL sheet by Manuel priocess's BIG job. So, can someone give me the query.

    Please try under queries

    The roles assigned to the list of Perm:

    SELECT B.ROLENAME

    OF PSCLASSDEFN A, PSROLECLASS B

    WHERE (A.CLASSID = B.CLASSID

    AND A.CLASSID =: 1).

    List of Perm pages can access:

    SELECT B.MENUNAME, B.BARNAME, B.BARITEMNAME, B.PNLITEMNAME, C.PAGEACCESSDESCR, B.DISPLAYONLY

    OF PSCLASSDEFN A, PSAUTHITEM B, PSPGEACCESSDESC C

    WHERE (A.CLASSID = B.CLASSID

    AND A.CLASSID =: 1

    AND B.BARITEMNAME > ' '

    AND B.AUTHORIZEDACTIONS = C.AUTHORIZEDACTIONS)

  • I found the solution for the problem of sound-acpi with Satellite P100-219

    Hello

    I found the solution for the problem of sound-acpi with Toshiba P100 (it works with P100-219 at least). I can provide the source modified and compiled table DSDT, but I would like to know if it is possible to get these changes in the next update of the BIOS?

    See you soon,.
    MIK

    Hi Mik

    As you know that it is not possible to find info on the next BIOS, especially if you want to have some information about the Linux operating system. Just wait and see if some forum users pointed out something on the subject.

  • How to set the clock for the hours, minutes, and seconds with Windows XP

    How to set the clock for the hours, minutes, and seconds with Windows XP

    I don't know of your question.  If you ask how to show the clock in the tray system with hours, minutes and seconds, then download & run "Tclock Light".  Windows will not natively display the seconds.

    TClock Light: <> http://homepage1.nifty.com/kazubon/tclocklight/index.html >

    HTH,
    JW

  • Why it takes so long for the BlackBerry vendor to deal with accounts?

    Why it takes so long for the BlackBerry vendor to deal with accounts?

    I put in my request 3 days ago, and it has not yet been verified.

    Hello

    Could you please PM me your name of the seller? Do you get the email that asks you to send the document ID/commercial? If this isn't the case, please try to chcek your spam folder.

    Kind regards

    Satya

  • Hello, I had paid for the creative but not access, with Juliette deroche sister cloud account, thank you

    Hello, I had paid for the creative but not access, with Juliette deroche sister cloud account, thank you

    A cloud subscription is linked to the Adobe ID of the person who purchased the subscription

    YOU can install and activate on 2 computers, but two activations cannot be used at the same time

    If you give your sister your credential, you can not both use your subscription at the same time

    Cloud license allows 2 activations http://www.adobe.com/legal/licenses-terms.html

    -Install on a 2nd computer http://forums.adobe.com/thread/1452292?tstart=0

    -Windows or Mac has no importance... 2 on the same operating system or 1 on each

    -Two activations may NOT be used at the same time (noted in the link above of the license)

  • FRM-30351: no list items defined for the list item

    Hello
    I used a dynamic list, and when I compile this message appears:
    FRM-30351: no list items defined for the list item.

    If the list is not needed, it's just a warning and you can ignore it.

  • How to build a list or a table with fixed values?

    Is it possible to create a list or a table with fixed values, but with a variable length?

    for example:

    var columns = "name, age, function;

    var insertParams = generateList ( listLen (columns), ',','.) » ); *

    fact: insertParams = ',?,??


    * (this function does not exist. This is just to illustrate what I need)

    I know that this feature is easily created by creating a loop, but I was wondering if it was possible with a single line of code.

    Thank you

    If he can generate a table in the same way, which would be as well.

    Our messages have clashed. But I think that repeatString() would do the trick. You could cut the rear comma with left() or convert it to a table. By default, ListToArray() will silently ignore the trailing comma.

  • How to display the line empty as a line with null values

    Hi all

    Pls advise me if it is possible to use a single query statement to display
    Empty row (i.e. not a single return line) as a line with null values.

    For example,.

    Select the names of names_mst whose name = "sgasfgs".

    Result:
    Names of
    =====
    < null >

    Hello
    If you desire to join external to double, as shown below, you still get at least a line of production

    SELECT  nm.names
    FROM            dual
    LEFT OUTER JOIN names_mst   nm  ON nm.name='sgasfgs';
    
  • Remove data with null value

    Hello

    I'm using Oracle 11 g. I have a table with an id of 3, node, the value column. Combination of the column id and node, that must be taken account for deletion on the registers.

    Here, I need to delete lines with the NULL value in the value column. If for a combination of id and node with non-null values, then I need to delete rows with a null value for this combination.

    If the combination of id, node is not null value then this records should not delete.

    Below table, I need to remove the second row, for which is a value not zero VOICE CAL '10' is there, so I need to delete the row with null values. (VOICE, CAL, NULL)

    Network, FL, there is no value is non-null then I should NOT delete this line.

    This table is to have 100 s of this association, we can delete data in a single delete query?

    Or how I can delete rows with nulls for this combination.

    Tab1

    VALUE OF THE NŒUD ID

    VOICE CAL 10
    VOICE CAL NULL
    NETWORK NULL FL

    Thank you

    Hello

    oradba11 wrote:

    Hello

    I'm using Oracle 11 g. I have a table with an id of 3, node, the value column. Combination of the column id and node, that must be taken account for deletion on the registers.

    Here, I need to delete lines with the NULL value in the value column. If for a combination of id and node with non-null values, then I need to delete rows with a null value for this combination.

    If the combination of id, node is not null value then this records should not delete.

    Below table, I need to remove the second row, for which is a value not zero VOICE CAL '10' is there, so I need to delete the row with null values. (VOICE, CAL, NULL)

    Network, FL, there is no value is non-null then I should NOT delete this line.

    This table is to have 100 s of this association, we can delete data in a single delete query?

    Or how I can delete rows with nulls for this combination.

    Tab1

    VALUE OF THE NŒUD ID

    VOICE CAL 10
    VOICE CAL NULL
    NETWORK NULL FL

    Thank you

    You can do this in a single DELETE statement (it is not a request), using an EXISTS or IN the subquery.  For example:

    REMOVE table_x m

    WHERE the value IS NULL

    AND THERE ARE)

    SELECT 0

    FROM table_x s

    WHERE s.id = m.id

    AND s.node = m.node

    AND s.value IS NOT NULL

    )

    ;

    If you would care to post CREATE TABLE and INSERT instructions for the sample data, and then I could test it.

  • ORDER BY a column with NULL values only

    Hello

    The order of column has all null values for the results of my query set.

    Ex:

    Select a, b, c from table1 where type = 'type1' and ID = "id1" order by column1

    In the above query, "column1" contains nulls for 'type1 '. The order of the records in the result set is different for different ID values if the values of a, b and c are always the same.
    What is happening in the 10g database.

    I have also observed that the order of the records for the same query conforms in the 9i database.

    (1) is the difference due to the difference in versions of database?
    (2) is there a way to get the order even records independently entry ID?
    (3) I cannot in the same order in 10 g DB too as the order in 9i DB?

    Thank you.

    Hello

    Madhuri says:
    Hello

    The order of column has all null values for the results of my query set.

    Ex:

    Select a, b, c from table1 where type = 'type1' and ID = "id1" order by column1

    In the above query, "column1" contains nulls for 'type1 '. The order of the records in the result set is different for different ID values if the values of a, b and c are always the same.
    What is happening in the 10g database.

    I have also observed that the order of the records for the same query conforms in the 9i database.

    If two or more rows have the same values (or NULL) for each ORDER BY expressions, then you may not be sure what order they will be. The system is free to do whatever he finds convenient. What the system identifies Dresser can vary depending on many factors, including the version, the size of the table, the conditions in the WHERE clause, there is a GROUP BY clause, or not... In all cases, it is not something that you can depend on. If you want the output in a certain order, to specify the order in the ORDER BY clause.

    (1) is the difference due to the difference in versions of database?

    Could be. In all versions, Oracle said that you cannot count on the order being compatible, except if the ORDER BY clause, it is consistent.

    (2) is there a way to get the order even records independently entry ID?

    Add more expressions at the end of the ORDER BY clause, as tie-breakers.
    For example:

    ORDER BY  column1
    ,         a
    ,         b
    ,         c
    

    If table1 is really a table (not a view), you can add a ROWID.
    In most cases, you can ORDER BY expressions that are not in the SELECT clause. So if you have a primary key, you can usually ORDER BY it, even if you don't see it.

    (3) I cannot in the same order in 10 g DB too as the order in 9i DB?

    Of course, ORDER BY works the same in all versions. If you have an ORDER BY clause to unambiguously, the output will be exactly the same order in any version.
    Remember that the absence of ORDER BY has no effect in all versions. If you have an ORDER BY of ambiguous clause, you can not count on the coming out in a particular order in any version.

  • Problem with regexp_substr if the string with null values between commas.

    Hi all

    My version of DB is 10.1.0.5.0
    I want to extract the string values using query below, but I am unable to provide the correct result.
    WITH t  AS ( select '123,1,3,22' col FROM DUAL
            UNION ALL
            SELECT '123,,2,1' FROM DUAL
            UNION ALL
            SELECT '5,1,2,,' FROM DUAL
            ) 
    SELECT regexp_substr(t.col,'[^,]*',1,1)
          ,regexp_substr(t.col,'[^,]*',1,2)
          ,regexp_substr(t.col,'[^,]*',1,3)
          ,regexp_substr(t.col,'[^,]*',1,4) FROM DUAL,t   ;
    My required result as below.
    123     1      3      22
    123            2       1
    5       1      2        
    Please help me to get the required result by using regular expressions.
    Thanks, Ram

    Hello

    In Oracle 10, you can do so by combining REGEXP_SUBSTR with something else like RTRIM:

    SELECT     RTRIM (REGEXP_SUBSTR (col, '[^,]*(,|$)', 1, 1), ',')     AS part_1
    ,     RTRIM (REGEXP_SUBSTR (col, '[^,]*(,|$)', 1, 2), ',')     AS part_2
    ,     RTRIM (REGEXP_SUBSTR (col, '[^,]*(,|$)', 1, 3), ',')     AS part_3
    ,     RTRIM (REGEXP_SUBSTR (col, '[^,]*(,|$)', 1, 4), ',')     AS part_4
    FROM     t
    ;
    

    Starting Oracle 11 REGEXP_SUBSTR alone can do.

    But look at the first response; regular expressions will be probably less effective than less powerful features, especially when all channels have the same number of separators.

    Published by: Frank Kulash on 29 December 2012 08:36

  • External table for the file delimmited by commas

    Im trying to create a table of externla for the comma-delimited file
    but it also has a scenario where the fields can have a comma between "" e.g.

    example of record
    1,one,first
    2,two,second
    3,three,third
    4,four,"4,fourth"
    Example of table
    create table ext_table_csv (
      i   Number,
      n   Varchar2(20),
      m   Varchar2(20)
    )
    organization external (
      type              oracle_loader
      default directory ext_dir
      access parameters (
        records delimited  by newline
        fields  terminated by ','
        missing field values are null
      )
      location ('file.csv')
    )
    reject limit unlimited;
    So when I question this record 4 table of Externla will be read as

    M/2
    i           n                      m
    4         four     "4
    {code}
    Above Ext table is just an example, Im adding bad file and log file in real table.
    
    Please help me if there is a way this can be resolved with external table.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        

    Change the definition of:

    FIELDS TERMINATED BY ', '.

    TO:

    FIELDS ENDED BY ',' POSSIBLY FRAMED BY "" "

  • A loop in a refcursor for the list of dates as a string

    Hello
    I have a simple procedure that gives me the list of dates and dates
    I need to get the dates dates separated by commas
    I don't know if this can be done directly by making a loop on the refcursor or I have to go pick her up in a file/table and then concatenate with comma, or is there anything else that can be done.
    I tried some stuff like below

    PS help out me
    the procedure is that returns the list of dates
    CREATE OR REPLACE procedure SALUSER.prm_sp_rpt_payslip_lop_dates(p_empid in int,p_tran_year in int,p_tran_month in integer,o_dates out sys_refcursor)
    as
    begin
     open o_dates for select  to_char(PHL_LOP_FROM,'DD-Mon-YYYY'),to_char(PHL_LOP_TO,'DD-Mon-yyyy') 
                     from prm_h_lop
                     where phl_emp_id=p_empid
                       and phl_tran_year=p_tran_year
                       and phl_Tran_month=p_tran_month;
    
                   
     end;
    /
    I need my o/p as
    dates :<date1>,<date2>...etc
    Kind regards

    Maybe sth. as

    SQL>  var cur refcursor
    
    SQL>  declare
     cr sys_refcursor;
     procedure prm_sp_rpt_payslip_lop_dates (cr in out sys_refcursor)
     as
     begin
       open cr for select hiredate from emp;
     end prm_sp_rpt_payslip_lop_dates;
    begin
     prm_sp_rpt_payslip_lop_dates(cr);
     open :cur for select 'Dates: ' || column_value dates from xmltable('string-join(//text(), ", ")' passing xmltype(cr));
    end;
    /
    PL/SQL procedure successfully completed.
    
    SQL>  print cur
    
    DATES
    --------------------------------------------------------------------------------
    Dates: 17-Dec-1980, 20-Feb-1981, 22-Feb-1981, 02-Apr-1981, 28-Sep-1981, 01-May-1
    981, 09-Jun-1981, 19-Apr-1987, 17-Nov-1981, 08-Sep-1981, 23-May-1987, 03-Dec-198
    1, 03-Dec-1981, 23-Jan-1982                                                     
    
    1 row selected.
    

Maybe you are looking for

  • Equivalent of Mac for gthumb

    Gthumb Linux is excellent for photos sort by date - is there a mac equivalent for gthumb? Thank you

  • L20-181: RAM is not properly recognized

    T L20 181 it is written in the properties, I've got 256 MB of ddr2 ram, but when I check on computer it shows only 190 MB of ram. There is no chipset or graphics card that supports the computer's memory in this model. so I'm interested ifI have been

  • How can I change the configuration for the output channels analog on a PXI-6704?

    I can't seem to understand how to access the configuration of the channels to the outputs analog (channel 33 and 35) for PXI-6704. This piece of test equipment is out of tolerance and must be calibrated. I have followed the procedure of calibration h

  • Its stopped working on computer

    I can hear the sound by clicking on and on when I turn the speakers market, especially when I plug phones head but the noise stopped on all my programs, Itunes, quicken, windows. Any suggestions?

  • WordWrap on desktop hp2510

    How do you turn OFF wordwrap on a deskjet hp 2510 please. I want to print a .txt (text) file. One solution would be to cut the file before printing (with a python for example script) on a line width max - but how many characters/line should there be?