How to split comma delimited string?

Hi,
I have a parameter called Id in my SP which will be of nvarchar data type and i'm going to get the multiple ids at a time seperated by commas in that parameter from the application. Now my requirement is to update a table with these comma seperated ids in seperate rows.
For example, if i have 2 parameters called Id1 and Id2. Id1 will contain only one value and will be of int data type and Id2 will be of nvarchar data type as i can get multiple ids delimited by a comma from the application. Suppose Id1 = 1 and Id2 = '1,2,3,4'. Then I have to update id2 in the tables seperately like wherever Id1 is '1' i need to update Id2 column for 4 rows with the value 1, 2, 3, 4 respectively in different rows.
Could you please tell me how can i do this in T-SQL? How can i split the data of parameter Id2 in 4 different rows?
Please let me know if you did not understand the question.
Thanks,
Deepti

 deeptideshpande wrote:
Hi,
I got a similar function which is like this:
CREATE FUNCTION dbo.fnSplit(
@sInputList VARCHAR(8000) -- List of delimited items
, @sDelimiter VARCHAR(8000) = ',' -- delimiter that separates items
) RETURNS @List TABLE (item VARCHAR(8000))
BEGIN
DECLARE @sItem VARCHAR(8000)
WHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0
BEGIN
SELECT
@sItem=RTRIM(LTRIM(SUBSTRING(@sInputList,1,CHARINDEX(@sDelimiter,@sInputList,0)-1))),
@sInputList=RTRIM(LTRIM(SUBSTRING(@sInputList,CHARINDEX(@sDelimiter,@sInputList,0)+LEN(@sDelimiter),LEN(@sInputList))))
IF LEN(@sItem) > 0
INSERT INTO @List SELECT @sItem
END
IF LEN(@sInputList) > 0
INSERT INTO @List SELECT @sInputList -- Put the last item in
RETURN
END
GO
Now when i use this in my select statement, i get data in a tabular structure as shown below:
select
from dbo.fnSplit('1,22,333,444,,5555,666',
Results
Item
1
22
333
444
5555
666
Now my requirement is to insert this value in a table which has 2 columns ID1 and ID2.
At any point of time ID1 will be an int value(only one id in that parameter) and ID2 can have multiple ids delimited by comma. With the help of above split function i can split values of ID2 into 6 different ids but i need to insert the table
in the following way:
ID1     ID2
1        1
1        22
1        333
1        444
1        5555
1        666
How can i insert the data in the above mentioned fashion.
Thanks,
Deepti
Like this:
Code Snippet
select 1 as id,* from dbo.fnSplit('1,22,333,444,,5555,666', ',')
Great!!!! Wonderfull!!!... Thanks a lot.

Similar Messages

  • Split Comma Delimited String Oracle

    I want to Split Comma Delimited string in oracle9i into rowwise data.i do not want to use Functions or connect by level...
    is there any other way from which we can split strings.???
    if we use Connect by level method the problem im facing is we cannot use suqueries in Connect by clause...
    Edited by: user11908943 on Sep 16, 2009 8:37 AM

    michaels2 wrote:
    I prefer using XMLTABLE which has superceded XMLSEQUENCE and I personally find it easier to read...Agree, but that would be hard in 9i since it is not implemented ;)Ah! missed that bit (gawd I wish people would upgrade to supported versions)
    In still later versions (11g) I prefer
    SQL>  with t as
    select 'a,b,c,d,e' str from dual
    select trim(column_value) str
    from t, xmltable(('"' || replace(str, ',', '","') || '"'))
    STR                                                                            
    a                                                                              
    b                                                                              
    c                                                                              
    d                                                                              
    e                                                                              
    5 rows selected.
    Natty! But completely illogical (I mean creating an XMLTABLE from a non-XML string). I'm guessing that's a development of XQuery?

  • How to split a delimited string into an array...

    I have a delimited string coming in to a stored procedure (SP) for vb.net that needs to be parsed/converted into multi-dimensional arrays. The reason I am using delimited string because I do not know how to pass arrays to oracle SP from vb.net using ODP or MPO (Microsoft's Provider for Oracle).
    My delimited string looks something like this: "level1_1|level2_1:level3_1;level3_2|level2_2:level3_1;level3_2~Level1_2|level2_2:level3_1"
    So, its going to be 3d array. I would greatly appreciate if anyone could help me solving this puzzle. Any examples would be a great help.
    Thanks for everything in advance,
    Vincent

    Hi Andrew,
    I appreciate your response. Currently I use "Microsoft provider for Oracle" to connect to Oracle Database because when I started with my application there wasn't ODP (Oracle Data Provider for .Net) available. So, I used Microsoft provider and still using it.
    I know how to use arrays in .Net but the problem is I can not find the Oracle Type to pass the array to Oralce Stored Procedure using this provider.
    It would be very helpful if someone shows me the syntax for both to receive from oracle and transport to Oracle. I haven't tried using ODP yet. May be now its the time to see how it works.
    And of course, your link was very helpful but I am already doing that (which is very slow for multi-dimentional array). So, I thought there might be a built in function in oracle which does that. Because most of the programming languages does have built in function for this conversion. for example: Split() in vb, java, javascript etc.
    Anyway, if anyone finds any clues as to how to pass milti-dimentional arrays from .Net (microsoft) to oracle stored procedure please, please let me know how to do that.
    -Vincent

  • How to split a delimited string into rows

    Hi Everyone,
    I have a field in my EMPLOYEE table named "OLD_USER_IDS" which stores all the old system ID's that the employee was once assigned to. This field is comma separated like so: "USERID1,USERID2,USERID3". My question is: how can I write a SELECT query that splits each individual User ID into its own row?
    For example:
    EMP_ID USER_ID
    10 USERID1
    10 USERID2
    12 USERID3
    15 USERID4
    15 USERID5
    15 USERID6
    Thank You
    -Sam

    I think you should search this forum first for similar questions. I keep track of some interesting stuffs posted in this forum in a file, and from that
    WITH t AS  (SELECT 'USER1,USER2,USER3' str FROM DUAL
    select substr(str,
                        decode(level,
                               1,
                               1,
                               instr(str, ',', 1, level - 1) + 1),
                        decode(instr(str, ',', 1, level),
                               0,
                               length(str),
                               instr(str, ',', 1, level) -
                               decode(level,
                                      1,
                                      0,
                                      instr(str, ',', 1, level - 1)) - 1)) the_value
            from (select str from t)
          connect by level <=
                     length(str) - length(replace(str, ',')) + 1;

  • DRM Function to divide comma delimited string to list value

    Hi
    Any one knows how to seperate comma delimited string into list values.
    Thanks

    Are you wanting to dynamically set the list values for a property? If so there are a couple options:
    1. You can update them via the API.
    2. You can write a sql script to update the table Property_List. This requires an application server restart and generally isn't recommended for support reasons but it makes sense in some instances.
    Edited by: Naren Truelove on 16/02/2011 22:08

  • Comma delimited string relating to subreports

    I previously opened a discussion called comma delimited string for a report header. The response I received then worked well for 'Year' but not for two other areas I am trying to use it for.
    Original Code
    Details:
    whileprintingrecords;
    stringvar Year:= Year+ {@Year} + ", ";
    Report Footer:
    whileprintingrecords;
    stringvar Year;
    Left(Year, len(Year)-2);
    I needed to modify the code to eliminate duplication in Year and this worked fine. See the code below. I also needed this code for two other areas, Author and School. Without the extra line of code with the 'instr' function the code would always show and error for ' Left(author, len(author)-2);'.  It came up with and error saying that the result was less than 0 or not and integer and went into debug mode. I added the instr function line and it worked for most but not all. This is my problem. Either the ' Left(author, len(author)-2);' line or 'If instr(author, {@Author } ) = 0 then' makes data disappear. It will show a comma delimited string for 'Author' on most rows but not from some. The same would be true for' School'. I am not sure what is going on. The code below is what I am currently using in the subreports.
    Details:
    whileprintingrecords;
    stringvar author;
    If instr(author, {@Author}) = 0 then
        author:= author + {@Author } + ", ";
    Report Footer:
    whileprintingrecords;
    stringvar author;
    If instr(author, {@Author } ) = 0 then
        author:= author + {@Author }  + ", ";
    Else
        Left(author, len(author)-2);

    Hi Abhilash,
    The code for the @Author is:
    If ({Command.chrStatus} = "External")then
        {Command.chrSurname} & ", " & {Command.chrFirstname}
    Else
        {Command.chrSurname(1)} & ", " & {Command.chrFirstname(1)}
    The goal of this code was to pull all the authors into one comma delimited string.
    eg Smith, Brian; Jones, Barry; Lee, Henry
    The same desire was with the Schools and the code was the same. I just don't know why this is returning the blanks.
    You mentioned in the last post that this would be better done in an SQL command. Should I open up another discussion because I think this would be the way to go. I just don't know how I can do the same comma delimited code in SQL.
    Thanks

  • Split commas delimited into 1D complex array

    I have comma delimited string in this format
    [0.866405665874481,0.127425819635391,0.983153462409973,-0.0711551383137703,0.955700755119324,-0.27884304523468,0.787182509899139,-0.501964211463928,0.512355387210846,-0.687117278575897,0.177220240235329,-0.777789652347565,-0.0876994803547859,-0.792799115180969,-0.324512422084808,-0.736825287342072,-0.517065346240997,-0.627932071685791,-0.666604995727539,-0.471743047237396,-0.767350137233734,-0.287838608026505,-0.819185018539429,-0.0853987112641335,-0.81872695684433,0.123056441545486,-0.761552691459656]
    The data contains pairs of complex numbers.  The first 2 numbers is one pair, next 2 numbers one pair, next pairs.....
    How can I extract the pairs of number and make it into a 1D complex array?
    This is the expected output:
    (0.866405665874481,0.127425819635391),(0.983153462409973,-0.0711551383137703),(0.955700755119324,-0.27884304523468),(0.787182509899139,-0.501964211463928),(0.512355387210846,-0.687117278575897),(0.177220240235329,-0.777789652347565),(-0.0876994803547859,-0.792799115180969),(-0.324512422084808,-0.736825287342072),(-0.517065346240997,-0.627932071685791),(-0.666604995727539,-0.471743047237396),(-0.767350137233734,-0.287838608026505),(-0.819185018539429,-0.0853987112641335),(-0.81872695684433),(0.123056441545486,-0.761552691459656)
    Any gurus pls advise
    Thanks and great day
    Solved!
    Go to Solution.

    I used the Spreadsheet String to Array, Decimate Array, and then Re/Im to Complex.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines
    Attachments:
    Delimited String to Complex Number Array.png ‏13 KB

  • Using a comma-delimited string in Dynamic SQL

    Hi --
    If I receive a comma-delimited string as an in parameter, can I simply use that (in string format) when building my dynamic sql?
    Thanks,
    Christine

    The problem is, that you can not use bind variables
    here, only literals. This causes
    eventual performance problems.And to avoid the inevitable database performance problems Dmytro mentions you can use a function to convert the string to a varray and select from that. This also avoids having to use dynamic sql.
    First you create a varray and conversion function.
    SQL> create or replace type tabstr_t as table of varchar2(255)
      2  /
    Type created.
    SQL> create or replace function tabstr (
      2      p_str in varchar2,
      3      p_sep in varchar2 default ','
      4      )
      5  return tabstr_t
      6  as
      7      l_str long default p_str || p_sep;
      8      l_tabstr tabstr_t := tabstr_t();
      9  begin
    10      while l_str is not null loop
    11          l_tabstr.extend(1);
    12          l_tabstr(l_tabstr.count) := rtrim(substr(
    13                  l_str,1,instr(l_str,p_sep)),p_sep);
    14          l_str := substr(l_str,instr(l_str,p_sep)+1);
    15      end loop;
    16      return l_tabstr;
    17  end;
    18  /
    Function created.Then you can use these in either regular sql.
    SQL> var s varchar2(100)
    SQL> exec :s := 'Smith,Scott,Miller'
    PL/SQL procedure successfully completed.
    SQL>
    SQL> select * from emp where ename in
      2      (select upper(column_value) from table(tabstr(:s)));
    EMPNO ENAME    JOB          MGR HIREDATE     SAL   COMM  DEPTNO
      7369 SMITH    CLERK       7902 17-DEC-80    800             20
      7788 SCOTT    ANALYST     7566 09-DEC-82   3000             20
      7934 MILLER   CLERK       7782 23-JAN-82   1300             10Or in pl/sql.
    SQL> var c refcursor
    SQL> begin
      2      open :c for
      3      select * from emp where ename in
      4          (select upper(column_value) from table(tabstr(:s)));
      5  end;
      6  /
    PL/SQL procedure successfully completed.
    SQL> print c
    EMPNO ENAME    JOB          MGR HIREDATE     SAL   COMM  DEPTNO
      7369 SMITH    CLERK       7902 17-DEC-80    800             20
      7788 SCOTT    ANALYST     7566 09-DEC-82   3000             20
      7934 MILLER   CLERK       7782 23-JAN-82   1300             10

  • Converting Floats to comma-delimited strings?

    Does anyone know of any methods or classes that can convert a float to a comma delimited string?
    Alternatively, conversion of a non-comma delimited string to a comma-delimited string would be just as good.
    An example of a comma-delimited string would be the display on the iPhone calculator.
    -- tia rick

    Also in this guide:
    https://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/DataFo rmatting/DataFormatting.html
    and a small example:
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
    //[numberFormatter setFormat:@"$#,##0;$#,##0;-$#,##0"];
    label.text = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:floatVal]];
    [numberFormatter release];
    notice the commented out line is commented out because apparently setFormat is not supported on the iPhone (yet???) It's what I really need.
    good luck

  • How do I split a comma delimited string into an array.

    I have a string that I am passing into a function that is Comma delimited. I want to split the string into an array. Is there a way to do this.
    Thanks in advance.

    trouble confirmed on 10gR1 and 10gR2
    works with 'a,b,c'  and also with  '  "1"  , "2"  ,  "3"  '
    does not work with '1,2,3' 
    throwing ORA-6512                                                                                                                                                                                                                                                                                                                           

  • Splitting of comma delimited string CONNECT BY Clause

    Hi ,
    I have got a problem in splitting a comma separated strings into rows .
    I am explaining the use case below :
    i have a table x_imp
    --> create table x_imp (id number, int_status varchar2(100),c_ref varchar2(30), s_ref varchar2(30));
    I inserted values into the table :
    insert into x_imp (id, int_status,c_ref,s_ref) values (1,'a1,a2,a3,a4','A','AS');
    insert into x_imp (id, int_status,c_ref,s_ref) values (1,'b1,b2,b3,b4','B', 'BS');
    insert into x_imp (id, int_status,c_ref,s_ref) values (1,'c1,c2,c3,c4', 'C', null);
    insert into x_imp (id, int_status, cust_ref, site_ref) values (1,NULL, 'D', NULL);
    I need to split the comma separated int_status into individual rows . That means my expected result is :
    . What I need or looking for as expected result:
    1, A, AS, a1
    1, A, AS, a2
    1, A, AS, a3
    1, A, AS, a4
    1, B, BS, b1
    1, B, BS, b2
    1, B, BS, b3
    1, B, BS, b4
    1, C, null, c1
    1, C, null, c2
    1, C, null, c3
    1, C, null, c4
    I currently have a solution using Regex . But this solution uses UNIQUE keyword .
    The solution i have currently :
    select UNIQUE c_ref,s_ref, regexp_substr(int_status,'[^,]+', 1, level) error_code
    from x_imp
    connect by regexp_substr(int_status, '[^,]+', 1, level) is not null;
    I need a better solution . Any pointers ?
    Thanks,
    Bibin

    One way of doing using MODEL clause:
    select c_ref, s_ref, res err_code
      FROM x_imp
    model
    partition by ( id, c_ref, s_ref)
    dimension by ( 1 rn)
    measures( int_status, cast(null as varchar2(100)) res,
              nvl(length(regexp_replace(int_status, '[^,]')),0)+1 nb )
    (res[for rn from 1 to nb[1] increment 1]=regexp_substr(int_status[1], '[^,]+', 1, cv(rn)))
    order by c_ref, s_ref;
    C_REF                          S_REF                          ERR_CODE                                                                                            
    A                              AS                             a3                                                                                                  
    A                              AS                             a4                                                                                                  
    A                              AS                             a1                                                                                                  
    A                              AS                             a2                                                                                                  
    B                              BS                             b2                                                                                                  
    B                              BS                             b1                                                                                                  
    B                              BS                             b3                                                                                                  
    B                              BS                             b4                                                                                                  
    C                                                             c4                                                                                                  
    C                                                             c3                                                                                                  
    C                                                             c1                                                                                                  
    C                                                             c2                                                                                                  
    D                                                                                                                                                                 
    13 rows selected

  • Rows to comma delimited string

    Oracle version Release 10.2.0.4.0
    i have the issue with the QuerySQL
    SQL returning comma delimited rate_codes for each (outlet, id_service)
    QuerySQL:
            select
                (select ltrim(MAX(SYS_CONNECT_BY_PATH(v.service,',')) KEEP (DENSE_RANK LAST ORDER BY curr),',') ratecodes
                  from (
                         select os.outlet, rsm.id_service, os.service,
                                row_number() OVER (PARTITION BY os.outlet, rsm.id_service ORDER BY os.service) AS curr,
                                row_number() OVER (PARTITION BY os.outlet, rsm.id_service ORDER BY os.service) -1 AS prev
                           from prcsd_outletsvcs_test os,
                                ratecode_service_mapping_test rsm
                           where os.corp                = to_number(substr(:account_number,1,5))
                           and os.house                 = ltrim(substr(:account_number,6,6),'0')
                           and os.cust                  = ltrim(substr(:account_number,12,2),'0')
                           and os.outlet                = :no_outlet
                           and rsm.corp                 = os.corp
                           and rsm.rate_code            = os.service
                           and rsm.id_service           = :id_service
                        ) v
                 group by outlet, id_service
                CONNECT BY prev = PRIOR curr
                START WITH curr = 1
                ) ratecodes
            from dual;parameter account_number 0787074919903, no_outlet=2, id_service=3 returns V1,XF
    parameter account_number 0787074919903, no_outlet=2, id_service=1 returns X1
    This sql works fine, but if i enclose it with another select ... dual and the QuerySQL in cursor like
    ( the parameters account_number, no_outlet and id_service is returned from some other tables in outer loop, here i am using outer dual to simulate my situation )
    select
        :no_outlet, :id_service,
        cursor (
                    QuerySQL above
                ) ratecodes
            from dual
        ) ratecodes
    from dual;cursor output:
    parameter account_number 0787074919903, no_outlet=2, id_service=3 returns V1,XF
    parameter account_number 0787074919903, no_outlet=2, id_service=1 returns nothing
    the (outlet,id_service) with only one rate_code is not returning anything
    data creation:
    CREATE TABLE PRCSD_OUTLETSVCS_TEST
      CORP     NUMBER                               NOT NULL,
      HOUSE    VARCHAR2(6 BYTE)                     NOT NULL,
      CUST     VARCHAR2(2 BYTE)                     NOT NULL,
      OUTLET   NUMBER                               NOT NULL,
      SERVICE  VARCHAR2(2 BYTE)                     NOT NULL
    CREATE TABLE RATECODE_SERVICE_MAPPING_TEST
      CORP        NUMBER(5),
      ID_SERVICE  NUMBER(10),
      RATE_CODE   VARCHAR2(10 BYTE)
    Insert into PRCSD_OUTLETSVCS_TEST(corp, house, cust, outlet, service)
    Values(7870, '749199', '3', 1, 'X1');
    Insert into PRCSD_OUTLETSVCS_TEST(corp, house, cust, outlet, service)
    Values(7870, '749199', '3', 1, 'X2');
    Insert into PRCSD_OUTLETSVCS_TEST(corp, house, cust, outlet, service)
    Values(7870, '749199', '3', 1, 'XC');
    Insert into PRCSD_OUTLETSVCS_TEST(corp, house, cust, outlet, service)
    Values(7870, '749199', '3', 2, 'V1');
    Insert into PRCSD_OUTLETSVCS_TEST(corp, house, cust, outlet, service)
    Values(7870, '749199', '3', 2, 'X1');
    Insert into PRCSD_OUTLETSVCS_TEST(corp, house, cust, outlet, service)
    Values(7870, '749199', '3', 2, 'X2');
    Insert into PRCSD_OUTLETSVCS_TEST(corp, house, cust, outlet, service)
    Values(7870, '749199', '3', 2, 'XF');
    Insert into PRCSD_OUTLETSVCS_TEST(corp, house, cust, outlet, service)
    Values(7870, '749199', '3', 3, '94');
    Insert into PRCSD_OUTLETSVCS_TEST(corp, house, cust, outlet, service)
    Values(7870, '749199', '3', 3, 'X1');
    Insert into PRCSD_OUTLETSVCS_TEST(corp, house, cust, outlet, service)
    Values(7870, '749199', '3', 3, 'X2');
    Insert into PRCSD_OUTLETSVCS_TEST(corp, house, cust, outlet, service)
    Values(7870, '749199', '3', 3, 'XR');
    Insert into RATECODE_SERVICE_MAPPING_TEST(corp, id_service, rate_code)
    Values(7870, 1, 'X1');
    Insert into RATECODE_SERVICE_MAPPING_TEST(corp, id_service, rate_code)
    Values(7870, 2, 'XC');
    Insert into RATECODE_SERVICE_MAPPING_TEST(corp, id_service, rate_code)
    Values(7870, 3, 'V1');
    Insert into RATECODE_SERVICE_MAPPING_TEST(corp, id_service, rate_code)
    Values(7870, 3, 'XF');
    Insert into RATECODE_SERVICE_MAPPING_TEST(corp, id_service, rate_code)
    Values(7870, 4, '94');
    Insert into RATECODE_SERVICE_MAPPING_TEST(corp, id_service, rate_code)
    Values(7870, 4, 'X1');
    Insert into RATECODE_SERVICE_MAPPING_TEST(corp, id_service, rate_code)
    Values(7870, 4, 'XR');thanks for any help

    pkchan wrote:
    i added
    where
    v.outlet        = svc_rc.outlet
    and v.id_service    = svc_rc.id_serviceand comment out the assignment lines with :no_outlet and :id_service
    You misunderstand how hierarchical query works. Look at:
                         select  max(ltrim(SYS_CONNECT_BY_PATH(v.service,','),',')) ratecodes
                            from (
                                  select  os.outlet,
                                          rsm.id_service,
                                          os.service,
                                          row_number() OVER (PARTITION BY os.outlet, rsm.id_service ORDER BY os.service) AS rn
                                    from  prcsd_outletsvcs_test os,
                                          ratecode_service_mapping_test rsm
                                    where os.corp        = to_number(substr(:account_number,1,5))
                                      and os.house       = ltrim(substr(:account_number,6,6),'0')
                                      and os.cust        = ltrim(substr(:account_number,12,2),'0')
                                      --and os.outlet      = :no_outlet
                                      and rsm.corp       = os.corp
                                      and rsm.rate_code  = os.service
                                      --and rsm.id_service = :id_service
                                 ) v
                            where
                                v.outlet        = svc_rc.outlet
                            and v.id_service    = svc_rc.id_service
                                CONNECT BY rn = PRIOR rn + 1
                                START WITH rn = 1WHERE clause in hierarchical query is applied AFTER hierarchy is build. Therefore rn=1 from EACH combination is joined to rn=2 in ALL combinations and then joined to rn=3 in ALL combinations, etc. and only then WHERE clause is applied. To create proper hierarchies you need:
                            where
                                v.outlet        = svc_rc.outlet
                            and v.id_service    = svc_rc.id_service
                               CONNECT BY outlet = PRIOR outlet
                                      AND id_service = PRIOR id_service
                                     AND rn = PRIOR rn + 1
                                START WITH rn = 1Now:
    with svc_rc as
        select distinct os.outlet, rsm.id_service
          from prcsd_outletsvcs_test os,
               ratecode_service_mapping_test rsm
         where rsm.corp       = os.corp
           and rsm.rate_code  = os.service
         order by outlet, id_service
    select
        svc_rc.outlet, svc_rc.id_service,
        cursor (
                select  (
                         select  max(ltrim(SYS_CONNECT_BY_PATH(v.service,','),',')) ratecodes
                            from (
                                  select  os.outlet,
                                          rsm.id_service,
                                          os.service,
                                          row_number() OVER (PARTITION BY os.outlet, rsm.id_service ORDER BY os.service) AS rn
                                    from  prcsd_outletsvcs_test os,
                                          ratecode_service_mapping_test rsm
                                    where os.corp        = to_number(substr(:account_number,1,5))
                                      and os.house       = ltrim(substr(:account_number,6,6),'0')
                                      and os.cust        = ltrim(substr(:account_number,12,2),'0')
                                      --and os.outlet      = :no_outlet
                                      and rsm.corp       = os.corp
                                      and rsm.rate_code  = os.service
                                      --and rsm.id_service = :id_service
                                 ) v
                            where
                                v.outlet        = svc_rc.outlet
                            and v.id_service    = svc_rc.id_service
                               CONNECT BY outlet = PRIOR outlet
                                      AND id_service = PRIOR id_service
                                     AND rn = PRIOR rn + 1
                                START WITH rn = 1
                        ) ratecodes
                  from  dual
               ) ratecodes
      from  svc_rc
        OUTLET ID_SERVICE RATECODES
             1          1 CURSOR STATEMENT : 3
    CURSOR STATEMENT : 3
    RATECODES
             1          2 CURSOR STATEMENT : 3
    CURSOR STATEMENT : 3
    RATECODES
             1          4 CURSOR STATEMENT : 3
    CURSOR STATEMENT : 3
    RATECODES
             2          1 CURSOR STATEMENT : 3
    CURSOR STATEMENT : 3
    RATECODES
             2          3 CURSOR STATEMENT : 3
    CURSOR STATEMENT : 3
    RATECODES
    V1,XF
             2          4 CURSOR STATEMENT : 3
    CURSOR STATEMENT : 3
    RATECODES
             3          1 CURSOR STATEMENT : 3
    CURSOR STATEMENT : 3
    RATECODES
             3          4 CURSOR STATEMENT : 3
    CURSOR STATEMENT : 3
    RATECODES
    94,X1,XR
    8 rows selected.
    SQL> You get 94,X1,XR, but still wrong results for other rows. So get rid of that extra level of select (we already established it is the source of the bug you are experiencing):
    with svc_rc as
        select distinct os.outlet, rsm.id_service
          from prcsd_outletsvcs_test os,
               ratecode_service_mapping_test rsm
         where rsm.corp       = os.corp
           and rsm.rate_code  = os.service
         order by outlet, id_service
    select
        svc_rc.outlet,
        svc_rc.id_service,
        cursor (
                select  ltrim(SYS_CONNECT_BY_PATH(v.service,','),',') ratecodes
                  from (
                        select  os.outlet,
                                rsm.id_service,
                                os.service,
                                row_number() OVER (PARTITION BY os.outlet, rsm.id_service ORDER BY os.service) AS rn
                          from  prcsd_outletsvcs_test os,
                                ratecode_service_mapping_test rsm
                          where os.corp        = to_number(substr(:account_number,1,5))
                            and os.house       = ltrim(substr(:account_number,6,6),'0')
                            and os.cust        = ltrim(substr(:account_number,12,2),'0')
                            and rsm.corp       = os.corp
                            and rsm.rate_code  = os.service
                       ) v
                  WHERE connect_by_isleaf = 1
                    AND outlet = svc_rc.outlet
                    AND id_service = svc_rc.id_service
                  START WITH rn = 1
                  CONNECT BY outlet = PRIOR outlet
                         AND id_service = PRIOR id_service
                         AND rn = PRIOR rn + 1
               ) ratecodes
      from  svc_rc
        OUTLET ID_SERVICE RATECODES
             1          1 CURSOR STATEMENT : 3
    CURSOR STATEMENT : 3
    RATECODES
    X1
             1          2 CURSOR STATEMENT : 3
    CURSOR STATEMENT : 3
    RATECODES
    XC
             1          4 CURSOR STATEMENT : 3
    CURSOR STATEMENT : 3
    RATECODES
    X1
             2          1 CURSOR STATEMENT : 3
    CURSOR STATEMENT : 3
    RATECODES
    X1
             2          3 CURSOR STATEMENT : 3
    CURSOR STATEMENT : 3
    RATECODES
    V1,XF
             2          4 CURSOR STATEMENT : 3
    CURSOR STATEMENT : 3
    RATECODES
    X1
             3          1 CURSOR STATEMENT : 3
    CURSOR STATEMENT : 3
    RATECODES
    X1
             3          4 CURSOR STATEMENT : 3
    CURSOR STATEMENT : 3
    RATECODES
    94,X1,XR
    8 rows selected.
    SQL> SY.

  • How to convert a delimited string to XML?

    Hi there,
    Please help me to convert a pipe delimited string into XML, e.g.
    string -------SubName:abc|SuvValue:123|
    required XML:
    <ROWS>
    <ROW>
    <SubName>abc</SubName>
    <SubValue>123</SubValue>
    </ROW>
    </ROWS>
    or
    string -------abc|123|
    required XML:
    <ROWS>
    <ROW>
    <SubName>abc</SubName>
    <SubValue>123</SubValue>
    </ROW>
    </ROWS>
    -----i am trying to first parse the string into a table type and then using the DBMS_XMLGen.getXML function but unable to get values from table type...
    any prompt response is highly appriciated...
    Regards, Hassan

    Hi Hassan,
    If your version supports it (ie 10gR2 and upwards), you can use XQuery to directly parse the string and generate the XML :
    SQL> SELECT XMLQuery(
      2   '<ROWS>
      3    <ROW> {
      4     for $i in ora:tokenize($str,"\|")
      5     return
      6      if ($i) then element {substring-before($i,":")} {substring-after($i,":")}
      7      else ()
      8   } </ROW>
      9   </ROWS>'
    10   passing sys_xmlgen('SubName:abc|SubValue:123|') as "str"
    11   returning content
    12  ).getClobVal()
    13  FROM dual;
    XMLQUERY('<ROWS><ROW>{FOR$IINO
    <ROWS><ROW><SubName>abc</SubName><SubValue>123</SubValue></ROW></ROWS>
    Each element is built based on its name from the input string.

  • How to parse a delimited string and insert into different columns?

    Hi Experts,
    I need to parse a delimited string ':level1_value:level2_value:level3_value:...' to 'level1_value', 'level2_value', etc., and insert them into different columns of one table as one row:
    Table_Level (Level1, Level2, Level3, ...)
    I know I can use substr and instr to get level value one by one and insert into Table, but I'm wondering if there's better ways to do it?
    Thanks!

    user9954260 wrote:
    However, there is one tiny problem - the delimiter from the source system is a '|' When I replace your test query with | as delimiter instead of the : it fails. Interestingly, if I use ; it works. See below:
    with t as (
    select 'str1|str2|str3||str5|str6' x from dual union all
    select '|str2|str3|str4|str5|str6' from dual union all
    select 'str1|str2|str3|str4|str5|' from dual union all
    select 'str1|str2|||str5|str6' from dual)
    select x,
    regexp_replace(x,'^([^|]*).*$','\1') y1,
    regexp_replace(x,'^[^|]*|([^|]*).*$','\1') y2,
    regexp_replace(x,'^([^|]*|){2}([^|]*).*$','\2') y3,
    regexp_replace(x,'^([^|]*|){3}([^|]*).*$','\2') y4,
    regexp_replace(x,'^([^|]*|){4}([^|]*).*$','\2') y5,
    regexp_replace(x,'^([^|]*|){5}([^|]*).*$','\2') y6
    from t;
    The "bar" or "pipe" symbol is a special character, also called a metacharacter.
    If you want to use it as a literal in a regular expression, you will need to escape it with a backslash character (\).
    Here's the solution -
    test@ORA11G>
    test@ORA11G> --
    test@ORA11G> with t as (
      2    select 'str1|str2|str3||str5|str6' x from dual union all
      3    select '|str2|str3|str4|str5|str6' from dual union all
      4    select 'str1|str2|str3|str4|str5|' from dual union all
      5    select 'str1|str2|||str5|str6' from dual)
      6  --
      7  select x,
      8         regexp_replace(x,'^([^|]*).*$','\1') y1,
      9         regexp_replace(x,'^[^|]*\|([^|]*).*$','\1') y2,
    10         regexp_replace(x,'^([^|]*\|){2}([^|]*).*$','\2') y3,
    11         regexp_replace(x,'^([^|]*\|){3}([^|]*).*$','\2') y4,
    12         regexp_replace(x,'^([^|]*\|){4}([^|]*).*$','\2') y5,
    13         regexp_replace(x,'^([^|]*\|){5}([^|]*).*$','\2') y6
    14  from t;
    X                         Y1      Y2      Y3      Y4      Y5      Y6
    str1|str2|str3||str5|str6 str1    str2    str3            str5    str6
    |str2|str3|str4|str5|str6         str2    str3    str4    str5    str6
    str1|str2|str3|str4|str5| str1    str2    str3    str4    str5
    str1|str2|||str5|str6     str1    str2                    str5    str6
    4 rows selected.
    test@ORA11G>
    test@ORA11G>isotope
    PS - it works for semi-colon character ";" because it is not a metacharacter. So its literal value is considered by the regex engine for matching.
    Edited by: isotope on Feb 26, 2010 11:09 AM

  • Comma Delimited String

    Hi Gurus,
    I have a problem:
    The following string has commas I want to break it as:
    'ABC,DEFGHI,DEE,YYY,XXX,333'
    'ABC'
    'DEFGHI'
    'DEE'
    'YYY'
    'XXX'
    '333'Any help will be highly appreciated.
    Thanks
    Aqil

    SQL> select * from v$version where rownum=1;
    BANNER
    Oracle8i Enterprise Edition Release 8.1.7.4.1 - Production
    SQL> select substr(col,instr(col,',',1,rownum)+1,instr(col,',',1,rownum+1)-instr(col,',',1,rownum)-1)
      2  from (select ','||'ABC,DEFGHI,DEE,YYY,XXX,333'||',' col from dual) a, all_objects b
      3  where rownum <= length(col)-length(replace(col,','))-1;
    SUBSTR(COL,INSTR(COL,',',1,R
    ABC
    DEFGHI
    DEE
    YYY
    XXX
    333
    6 rows selected.
    SQL> Nicolas.

Maybe you are looking for

  • MB5B problem

    i have a problem with stock on posting date. when i run a program to get information for the last month 2 times, it shows me different opening quantity. what the problem with this report when i run on day time.

  • Down payment (F-48)   for Asset Purchase Order

    Dear Experts, Please guide me,   i  am getting one error while doing down payment to  vendor through F-48 ,    I created one asset purchase order,  against purchase order making down payment that time  i am getting this  error message "You cannot use

  • Bug in Signatures preventing sending of mail?

    When I send mail using a signature, the message leaves as if it was sent (according to the Mail Activity bar) but it +never arrives at its destination+. I receive +no alert+ that the mail was not sent, and no bounce backs or error messages. If I dele

  • Help with Web link sharing

    I run an organization where documents are gathered and viewed on our website. Adobe.com has the perfect design and feel. But when i 'Copy URL' to the website link, I get an 'invalid address' message. The people at Wix told me it is probably because t

  • Default Batch in Production order

    Hello In the component screen of a production we can find a field called Batch. Now Iam populating value to this field manually while I create the order. I dont have batch management. I am creating valuation types and this valuation type I populate m