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

Similar Messages

  • 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 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?

  • 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

  • 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

  • Using a comma seprated string as rows

    i hv a column in which i store comma seprated name, i have to show them as rows in a report..
    plz help

    As with most things, it depends greatly on your Oracle version (you should always post this information).
    In release 11 here's a neat method.
    http://laurentschneider.com/wordpress/2009/07/select-from-column-separated-list.html
    In release 10 there's REGEXP
    http://nuijten.blogspot.com/2009/07/splitting-comma-delimited-string-regexp.html
    And it looks like you've been given a pre-10 answer already.

  • 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 use the column names generated from Dynamic SQL

    Hi,
    I have a problem with Dynamic SQL.
    I have written an SQL which will dynamically generate the Select statement with from and where clause in it.
    But that select statement when executed will get me hundreds of rows and i want to insert each row separately into one more table.
    For that i have used a ref cursor to open and insert the table.
    In the select list the column names will also be as follows: COLUMN1, COLUMN2, COLUMN3,....COLUMNn
    Please find below the sample code:
    TYPE ref_csr IS REF CURSOR;
    insert_csr ref_csr;
    v_select VARCHAR2 (4000) := NULL;
    v_table VARCHAR2 (4000) := NULL;
    v_where VARCHAR2 (4000) := NULL;
    v_ins_tab VARCHAR2 (4000) := NULL;
    v_insert VARCHAR2 (4000) := NULL;
    v_ins_query VARCHAR2 (4000) := NULL;
    OPEN insert_csr FOR CASE
    WHEN v_where IS NOT NULL
    THEN 'SELECT '
    || v_select
    || ' FROM '
    || v_table
    || v_where
    || ';'
    ELSE 'SELECT ' || v_select || ' FROM ' || v_table || ';'
    END;
    LOOP
    v_ins_query :=
    'INSERT INTO '
    || v_ins_tab
    || '('
    || v_insert
    || ') VALUES ('
    || How to fetch the column names here
    || ');';
    EXECUTE IMMEDIATE v_ins_query;
    END LOOP;
    Please help me out with the above problem.
    Edited by: kumar0828 on Feb 7, 2013 10:40 PM
    Edited by: kumar0828 on Feb 7, 2013 10:42 PM

    >
    I Built the statement as required but i need the column list because the first column value of each row should be inserted into one more table.
    So i was asking how to fetch the column list in a ref cursor so that value can be inserted in one more table.
    >
    Then add a RETURNING INTO clause to the query to have Oracle return the first column values into a collection.
    See the PL/SQL Language doc
    http://docs.oracle.com/cd/B28359_01/appdev.111/b28370/returninginto_clause.htm#sthref2307

  • How to escape a single quotes from a string of dynamic sql clause?

    if a single quotes exist in a dynamic sql clause for a string,
    like
    v_string :='select tname from tab where tabtype='table'',
    there tabtype='table' will conflict with the single quote ahead.
    could somebody tell me how to escape this single quotes?
    thanks for your tips,
    frederick

    fredrick,
    To represent one single quotation mark within a literal, enter two single quotation marks. For example :
    v_string :='select tname from tab where tabtype=''table'''
    Regards,
    Srinivas

  • Using bind variables (in & out) with dynamic sql

    I got a table that holds pl/sql code snippets to do validations on a set of data. what the code basically does is receiving a ID and returning a number of errors found.
    To execute the code I use dynamic sql with two bind variables.
    When the codes consists of a simpel query, it works like a charm, for example with this code:
    BEGIN
       SELECT COUNT (1)
       INTO :1
       FROM articles atl
       WHERE ATL.CSE_ID = :2 AND cgp_id IS NULL;
    END;however when I get to some more complex validations that need to do calculations or execute multiple queries, I'm running into trouble.
    I've boiled the problem down into this:
    DECLARE
       counter   NUMBER;
       my_id     NUMBER := 61;
    BEGIN
       EXECUTE IMMEDIATE ('
          declare
             some_var number;
          begin
          select 1 into some_var from dual
          where :2 = 61;
          :1 := :2;
          end;
          USING OUT counter, IN my_id;
       DBMS_OUTPUT.put_line (counter || '-' || my_id);
    END;this code doesn't really make any sense, but it's just to show you what the problem is. When I execute this code, I get the error
    ORA-6537 OUT bind variable bound to an IN position
    The error doesn't seem to make sense, :2 is the only IN bind variable, and it's only used in a where clause.
    As soon as I remove that where clause , the code will work again (giving me 61-61, in case you liked to know).
    Any idea whats going wrong? Am I just using the bind variables in a way you're not supposed to use them?
    I'm using Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit

    Correction. With execute immediate binding is by position, but binds do not need to be repeated. So my statement above is incorrect..
    You need to bind it once only - but bind by position. And the bind must match how the bind variable is used.
    If the bind variable never assigns a value in the code, bind as IN.
    If the bind variable assigns a value in the code, bind as OUT.
    If the bind variable assigns a value and is used a variable in any other statement in the code, bind as IN OUT.
    E.g.
    SQL> create or replace procedure FooProc is
      2          cnt     number;
      3          id      number := 61;
      4  begin
      5          execute immediate
      6  'declare
      7          n       number;
      8  begin
      9          select
    10                  1 into n
    11          from dual
    12          where :var1 = 61;       --// var1 is used as IN
    13 
    14          :var2 := n * :var1;     --// var2 is used as OUT and var1 as IN
    15          :var2 := -1 * :var2;    --// var2 is used as OUT and IN
    16  end;
    17  '
    18          using
    19                  in out id, in out cnt;  --// must reflect usage above
    20 
    21          DBMS_OUTPUT.put_line ( 'cnt='||cnt || ' id=' || id);
    22  end;
    23  /
    Procedure created.
    SQL>
    SQL> exec FooProc
    cnt=-61 id=61
    PL/SQL procedure successfully completed.
    SQL>

  • 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

  • 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.

  • Using a record as parameter in dynamic SQL

    Hi,
    I'm trying to pass a record (%rowtype) as parameter
    to a procedure which i call from inside a dynamic statement. This doesnt seem to work however, I get the reply "not a valid sql-statement".
    Apparently, Oracle does not allow for this since records are not a SQL-type but a PL/SQL-type.
    Have anyone found a way around this?
    (Except for the obvious to pass just the primary key and
    populate the record inside the procedure).
    The code looks like:
    declare
    v_rec employee%rowtype;
    v_stmt varchar2(500);
    begin     
    select *
              into v_rec
              from emplyee
              where rownum = 1;
    v_stmt := 'some_proc ( :param )';
    execute immediate v_stmt using v_rec;
    end;
    Any advice appreciated,
    Thanks
    Anders Grusell

    Hi,
    Here's a example of something similar which we had done for the data conversion excercise recently.
    The script uses dynmanic PL/SQL block and executes it using Execute Immediate. AAnd within the dynamic PL/SQL block, a procedure Pr_Pb_Test is called which takes in %ROWTYPE as ainput parameter.
    See if this helps.
    -- Shailender Mehta --
    Set ServerOutput On Size 999999;
    Declare
    i Number;
    lValue Varchar2(10);
    type rc is ref cursor;
    iVar1 Varchar2(10) := 'Test Var';
    l_cursor rc;
    ltest1 Mr_Test1%RowType; -- RowType Structure for Mirror
    lSql Varchar2(100);
    lNewTab Tb_Test%RowType; -- RowType Structure for the New System Table
    /* This procedure uploads to new system table the 1st time
    The table Test1 after successful upload will be taken Offline
    or deleted
    Procedure abc Is
    lSqlStr Long;
    Begin
    SQL> desc test1;
    Name Null? Type
    ID NUMBER
    COL1 VARCHAR2(10)
    lSqlStr := 'Declare
    ltest Test1%RowType;
    type rc is ref cursor;
    l_cursor rc;
    lNewTab Tb_Test%RowType; -- RowType Structure for new system Table
    Begin
    Open l_cursor For :lSql;
    Loop
    Fetch l_cursor Into ltest;
    Exit When l_cursor%NotFound;
    lNewTab.Id := ltest.Id;
    lNewTab.Col1 := ltest.Col1;
    -- Procedure which inserts into the new system
    -- table using %ROWTYPE
    Pr_Tb_Test (lNewTab);
    End Loop;
    End;
    Execute Immediate lSqlStr USING lsql;
    End abc;
    Begin
    Begin
    Select code_value
    Into lValue
    From DC_CODES
    Where code_type_cd = 'LASTRUNDT'
    And code_value Is Not Null;
    i := 1;
    Exception
    When No_Data_Found Then i := 0;
    End;
    If ( i = 0 ) Then
    Delete From Tb_Test;
    lSql := 'Select * from test1';
    abc;
    Else
    -- Subsequent uploads to the new system tables using MIRROR table : Mr_Test1
    SQL> desc mr_test1;
    Name Null? Type
    ID NUMBER
    COL1 VARCHAR2(10)
    ACTION_TYPE VARCHAR2(1)
    lSql := 'Select * from mr_test1 Where Action_Type = ''I''';
    Open l_cursor for lSql;
    Loop
    Fetch l_cursor Into ltest1;
    Exit When l_cursor%NotFound;
    lNewTab.Id := ltest1.Id;
    lNewTab.Col1 := ltest1.Col1;
    Pr_Tb_Test (lNewTab); -- Procedure which inserts into the new system
    End Loop;
    Close l_cursor;
    End If;
    Update dc_codes set code_value = sysdate;
    End;
    /

  • 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

  • SQL Statement error - ORA-00903: invalid table name

    Hi I have written a sql script that gets executed from a form within e-business suite. Unfortunately, the script is falling over with an error: unknown command beginning "MERGE INTO..." - rest of line ignored. unknown command beginning "USING edop...

  • Help! Question about Java Server Pages

    Hi everybody! I'm new to Java, and I wonder if anybody could help me with this: I need to know the "extension" of this file (I don't physically have the file, I have only its contents!): </GX> <GX ID=Beetle> <BR> Thank you for choosing <GX TYPE=cell

  • How can I get a replacement laptop battery for my Compac Presario CQ61?

    My computer alerted me to the fact that I had to replace my laptop battery ( it had a cross whenever i was charging it), then my computer went dead and i haven't been able to turn it on. Can I buy a laptop battery from the HP website? Product name Co

  • Add new batch during count entry (for cycle count by quant LICC)

    Hi! We are using LICC for cycle counting by quant as we have mixed storage and do not want to count all the materials in a single bin. Most of the materials involved are batch-managed. One issue we have is we may discover other batches during stock t

  • Call BAPI in Explorer

    Hi, I want to call / run  BAPI in Internet Explorer. Is it possible? Can anyone help me what kind of configuration is require for that? Regards, Nisit