Delimited list

Hi all,
I'm attempting to get out of the procedural programmer rut of performing loops for things that could be done in a single SQL statement.
I'd like to produce a delimited string from a list of results from a list of results.
current code is:
foo_string varchar2(100);
begin
for v_cur in (select foo from foobar) loop
foo_string := foo_string ||', '||v_cur.foo;
end loop;
end;
my dumb procedural programmer brain can't fathom how it could be done otherwise. I'm using oracle 9.

maybe this example might be of some help.
SQL> select * from pivot_tab;
      COL1 COL2
         1 a
         1 b
         1 c
         2 h
         2 h
SQL>
SQL>
SQL> select p.col1,
  2         substr(max(substr(sys_connect_by_path (p.col2,','),2)),1,60)
  3         as col2
  4    from (select col1,
  5                 col2,
  6                 row_number() over (partition by col1 order by col1, col2) rn
  7            from pivot_tab) p
  8  start with p.rn = 1
  9  connect by p.rn = prior p.rn + 1
10  and prior p.col1 = p.col1
11  group by col1;
      COL1 COL2
         1 a,b,c
         2 h,h
SQL>

Similar Messages

  • Convert delimited list of numbers from function to use in SELECT IN () quer

    Hey guys,
    I have to create a view based on some conditions. I have to get only the rows with specific IDs. I do the calculations for the logic using a function which returns a delimited list of the IDs. When I use this string in the query, it gives me a "Invalid Number" error.
    Here's the skeleton
    Select table1.col, table2.col1, table2.col2, table2.col3
    from table1, table2
    where table2.col1 in (function(table1.col))
    function() returns 12,34,564,7657 ....
    The reason that I am using a function to get the IDs is that the logic involved is complicated to get the right IDs. Any help would be appreciated
    Thanks,
    -P

    You can do this.
    select emp.* from  emp,
    table (sys.dbms_debug_vc2coll (7499,7788,7934))
    where empno = column_value
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
          7499 ALLEN      SALESMAN        7698 20-FEB-81       1600        300         30
          7788 SCOTT      ANALYST         7566 19-APR-87       3630                    20
          7934 MILLER     CLERK           7782 23-JAN-82       1300    

  • Group and Merge Delimited List

    Hi All
    Is there a way we can sort the result of Group and Merge processor->Delimited list values ?
    I see none in the options and it seems sorting them in alphabetical order.
    Thanks,
    Sid

    Hi Sid,
    Yes, the "Delimited List" selection function in Group and Merge sorts the results into ascending alphabetical order. This was a deliberate decision so that the results of the processor are deterministic and agnostic of the order of the records entering the processor. It is not possible to change this sort order inside the processor but if required you can perform downstream post-processing of the data if you need to change the order.
    thanks,
    Nick

  • PL/SQL function returning a colon delimited list of headings

    Hello,
    Apex version 4.1.0.23. I am editing an existing classic report which has the column heading option set to 'PL/SQL function returning a colon delimited list of headings'. I have been looking for some time but I cannot find where this PL/SQL function is defined. Can any one point me to the right direction? I do not see anything in the documentation either.
    Thanks,
    Usman

    Hi Usman,
    I looked into this issue and found that there's some JavaScript code executed when opening the page with the PL/SQL headings option enabled, or when selecting that option after loading the page, and this JavaScript attempts to set a background color for the column heading fields. Since we only display attributes for up to 100 columns, this JavaScript fails once you have more than 100 columns.
    I would certainly agree with Tony that 60 or 100 columns are a bit much. But there should be some indication why something is not working, even if it's only a message stating that there's only a certain number of columns supported. So I'll log a bug to improve this in APEX 5.0.
    Thanks,
    Marc

  • Query a comma delimited list

    Suppliers is a field containing a comma delimited list of
    Supplier ID's.
    When a supplier logs in they should be able to view all the
    auctions that they have been registered for
    i.e if their supplierID is in the suppliers field.
    have tried this and get an error:
    <CFQUERY NAME="GetAuctions"
    DATASOURCE="#Application.Datasource#">
    SELECT * FROM Auctions
    WHERE '#Session.SupplierID#' IN 'Auctions.Suppliers'
    </CFQUERY>
    have tried this and recordcount is 0 when it should be 3:
    <CFQUERY NAME="GetAuctions"
    DATASOURCE="#Application.Datasource#">
    SELECT * FROM Auctions
    WHERE '#Session.SupplierID#' LIKE 'Auctions.Suppliers'
    </CFQUERY>

    You should avoid having a list value in a field and normalise
    your table. But if you want to stick with your style(which is not
    advisable), maybe you can do this. I believe your supplier id is a
    string so the code below may cause slowness in your system:
    <CFQUERY NAME="GetAuctions1"
    DATASOURCE="#Application.Datasource#">
    SELECT Suppliers FROM Auctions
    </CFQUERY>
    <cfoutput query="GetAuctions1">
    <CFQUERY NAME="GetAuctions2"
    DATASOURCE="#Application.Datasource#">
    SELECT * FROM Auctions
    WHERE '#Session.SupplierID#' IN(<cfqueryparam
    values="#Suppliers#" cfsqltype="CF_SQL_VARCHAR" list="Yes">)
    </CFQUERY>
    </cfoutput>
    But if your supplier id is a numeric value. then you can do
    this:
    <CFQUERY NAME="GetAuctions"
    DATASOURCE="#Application.Datasource#">
    SELECT A1.* FROM Auctions A1
    WHERE #Session.SupplierID# IN(SELECT A2.Suppliers FROM
    Auctions A2 WHERE A2.your_primary_key_for_table_Auctions =
    A1.your_primary_key_for_table_Auctions)
    </CFQUERY>

  • Too many commas in my comma delimited list

    I'm trying to merge several pdf files into one by using the cfpdf tag (action="merge").  In the source attribute, you can enter a comma delimited list of file paths to merge the pdf files together.  I'm thinking that Adobe could have picked a better delimiter though because it breaks if there is a comma any one of the file names.  I've tried using replace() to replace the commas in my filenames with chr(44) before passing it to the cfpdf tag, but it still breaks.  Any ideas on how to accommodate this?  I'm trying to prevent having to copy hundreds of files to a temp directory, then use the directory attribute instead, then delete the temp directory.  That just seems like such a waste of resources...
    Thanks!

    cfpdfparam is a WIN!  Thanks for the heads up, i had no idea that you could use the tag like that.
    <cfpdf 
    action = "merge"
    destination = "C:\Inetpub\mydir\secure\test\output_merge.pdf"
    overwrite = "yes">
    <cfpdfparam source = "C:\Inetpub\mydir\secure\test\0003. A-001 - Restaurant, Floor Plan.pdf">
    <cfpdfparam source = "#expandPath('/secure/test/0001. G-001 - General.pdf')#">
    <cfpdfparam source = "#expandPath('/secure/test/0002. G-101 - General Information.pdf')#"></cfpdf>
    Works Great, Thanks!

  • Is it possible to convert a table of values into a comma-delimited-list?

    Hi,
    I'd like to turn the following dataset:
    Parent | Child
    Charles | William
    Charles | Harry
    Anne | Peter
    Anne | Zara
    Andrew | Beatrice
    Andrew | Eugenie
    into this:
    Parent | Children
    Charles | Diana,Camilla
    Anne | Peter,Zara
    Andrew | Beatrice,Eugenie
    In other words, I'd like to take a list of values pertaining to some key and produce them as a comma-delimited-list.
    I know its is possible in T-SQL although the method is a bit of a nasty hack. Is it possible in PL-SQL?
    Thaks in advance
    Jamie

    Hi,
    With model clause (10g)
    with t  as(
    select 'Charles' parent, 'William' child from dual union
    select 'Charles', 'Harry' from dual union
    select 'Anne', 'Peter' from dual union
    select 'Anne', 'Zara' from dual union
    select 'Andrew', 'Beatrice' from dual union
    select 'Andrew', 'Eugenie' from dual
    select parent,substr(res,2) res
    from t
    model
    return updated rows
    partition by ( parent)
    dimension by ( row_number()over(partition by parent order by child) rn)
    measures(child, cast( null as varchar2(4000)) as res)
    rules
    iterate(100000)
    until(presentv(res[iteration_number+2],1,0)=0)
    ( res[0]=res[0]||','||child[iteration_number+1]);
    PARENT  RES                                              
    Anne    Peter,Zara                                       
    Andrew  Beatrice,Eugenie                                 
    Charles Harry,William                                    
    3 rows selected.

  • REGEXP_SUBSTR for comma delimited list with null values

    Hi,
    I have a column which stores a comma delimited list of values. Some of these values in the list may be null. I'm having some issues trying to extract the values using the REGEXP_SUBSTR function when null values are present. Here are two things that 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 FFFAs you can see neither of the calls works correctly. Does anyone know how to modify the regular expression pattern to handle null values? I've tried various other patterns but was unable to get anyone to work for all cases.
    Thanks,
    Martin
    http://www.ClariFit.com
    http://www.TalkApex.com

    Hi, Martin,
    This does 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 just 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 query was that it was looking for sub-strings of 0 or more non-commas. There was such as sub-string. consisting of 3 characters, starting at position 1, so it returned 'AAA', as expected. Then there was another sub-string, of 0 characters, starting at position 4, so it returned NULL. Then there was a sub-string of 3 characters starting at position 5, so it returned 'BBB'.
    The problem with your 2nd query was that it was looking for 1 or more non-commas. 'DDD' is the 3rd such sub-string.
    Edited by: Frank Kulash on Feb 16, 2012 11:36 AM
    Added Oracle 11 example

  • Use PL/SQL Table values as a comma delimited list in a in (...) clause

    Hi,
    One my procedure's parameters is a PL/SQL table of id's (NUMBER) that the GUI sends it, based on the user's selections.
    Now, I want to use the table's values in my select's where clause to return only the correct records.
    However,
    select ......
    from ....
    where id in (i_array_ids)
    doesn't work of course, and my attempts of transfering the ids to a comma delimited list of numbers (as opposed to a lenghty varchar2 string) that could work between the ( ) have all failed.
    Thanks

    And here's an example I gave with some more up-to-date syntax than in that old AskTom thread:
    Re: DYNAMIC WHERE CLAUSE in PROCEDURE

  • Delimited list output

    I'd like to get a comma-delimited list of user email addresses from a table. I want to do it in a single select since I'm going to embed it into anther select. In SQL Server the following works:
    create table users (user_id varchar(10), email varchar(100))
    declare @email varchar(2000)
    SELECT @email = @email + email + '; ' FROM users
    How can I do this in Oracle (8i)?

    It sounds like you need Tom Kyte's str2tbl function as well as his stragg function. In the following example, I just left out the additional tables and join conditions, but it should work the same with them.
    scott@ORA92> -- test table and test data:
    scott@ORA92> create table hts_assay -- ha
      2    (assay_name varchar2(5),
      3       assay_id   varchar2(10),
      4       assay_type     varchar2(100))
      5  /
    Table created.
    scott@ORA92> insert all
      2  into hts_assay values ('name1', 'id1', 'type1a')
      3  into hts_assay values ('name1', 'id1', 'type1b')
      4  into hts_assay values ('name1', 'id1', 'type1c')
      5  into hts_assay values ('name2', 'id2', 'type2a')
      6  into hts_assay values ('name2', 'id2', 'type2b')
      7  into hts_assay values ('name3', 'id3', 'type3')
      8  into hts_assay values ('name4', 'id4', 'type4')
      9  select * from dual
    10  /
    7 rows created.
    scott@ORA92> commit
      2  /
    Commit complete.
    scott@ORA92> --
    scott@ORA92> -- code from Tom Kyte for stragg function:
    scott@ORA92> create or replace type string_agg_type as object
      2  (
      3       total varchar2(4000),
      4 
      5       static function
      6            ODCIAggregateInitialize(sctx IN OUT string_agg_type )
      7            return number,
      8 
      9       member function
    10            ODCIAggregateIterate(self IN OUT string_agg_type ,
    11                        value IN varchar2 )
    12            return number,
    13 
    14       member function
    15            ODCIAggregateTerminate(self IN string_agg_type,
    16                          returnValue OUT  varchar2,
    17                          flags IN number)
    18            return number,
    19 
    20       member function
    21            ODCIAggregateMerge(self IN OUT string_agg_type,
    22                      ctx2 IN string_agg_type)
    23            return number
    24  );
    25  /
    Type created.
    scott@ORA92> create or replace type body string_agg_type
      2  is
      3 
      4  static function ODCIAggregateInitialize(sctx IN OUT string_agg_type)
      5  return number
      6  is
      7  begin
      8        sctx := string_agg_type( null );
      9        return ODCIConst.Success;
    10  end;
    11 
    12  member function ODCIAggregateIterate(self IN OUT string_agg_type,
    13                             value IN varchar2 )
    14  return number
    15  is
    16  begin
    17        self.total := self.total
    18        || ','
    19        || value;
    20        return ODCIConst.Success;
    21  end;
    22 
    23  member function ODCIAggregateTerminate(self IN string_agg_type,
    24                               returnValue OUT varchar2,
    25                               flags IN number)
    26  return number
    27  is
    28  begin
    29        returnValue := ltrim(self.total,',');
    30        return ODCIConst.Success;
    31  end;
    32 
    33  member function ODCIAggregateMerge(self IN OUT string_agg_type,
    34                           ctx2 IN string_agg_type)
    35  return number
    36  is
    37  begin
    38        self.total := self.total || ctx2.total;
    39        return ODCIConst.Success;
    40  end;
    41 
    42 
    43  end;
    44  /
    Type body created.
    scott@ORA92> CREATE or replace
      2  FUNCTION stragg(input varchar2 )
      3  RETURN varchar2
      4  PARALLEL_ENABLE AGGREGATE USING string_agg_type;
      5  /
    Function created.
    scott@ORA92> -- code from Tom Kyte for str2tbl function:
    scott@ORA92> create or replace type myTableType as table of varchar2(100);
      2  /
    Type created.
    scott@ORA92> create or replace function str2tbl( p_str in varchar2 )
      2  return myTableType
      3  as
      4        l_str      long default p_str || ',';
      5        l_n         number;
      6        l_data    myTableType := myTabletype();
      7  begin
      8        loop
      9            l_n := instr( l_str, ',' );
    10            exit when (nvl(l_n,0) = 0);
    11            l_data.extend;
    12            l_data( l_data.count ) := ltrim(rtrim(substr(l_str,1,l_n-1)));
    13            l_str := substr( l_str, l_n+1 );
    14        end loop;
    15        return l_data;
    16  end;
    17  /
    Function created.
    scott@ORA92> --
    scott@ORA92> -- usage of stragg and str2tbl functions within a procedure
    scott@ORA92> -- that has a ref cursor as an out parameter
    scott@ORA92> CREATE OR REPLACE PROCEDURE your_procedure
      2    (xcur_spcur  OUT sys_refcursor,
      3       p_assaylist IN     VARCHAR2)
      4  AS
      5  BEGIN
      6    OPEN xcur_spcur FOR
      7    SELECT ha.assay_name, STRAGG (ha.assay_type) AS AssayResultTypes
      8    FROM   hts_assay ha
      9    WHERE  ha.assay_id IN
    10             (SELECT *
    11              FROM   TABLE (CAST (str2tbl (p_assaylist) AS mytableType)))
    12    GROUP  BY ha.assay_name;
    13  END your_procedure;
    14  /
    Procedure created.
    scott@ORA92> SHOW ERRORS
    No errors.
    scott@ORA92> VARIABLE g_ref REFCURSOR
    scott@ORA92> VARIABLE g_assaylist VARCHAR2(60)
    scott@ORA92> EXEC :g_assaylist := 'id1,id2,id3'
    PL/SQL procedure successfully completed.
    scott@ORA92> EXECUTE your_procedure (:g_ref, :g_assaylist)
    PL/SQL procedure successfully completed.
    scott@ORA92> PRINT g_ref
    ASSAY ASSAYRESULTTYPES
    name1 type1a,type1b,type1c
    name2 type2a,type2b
    name3 type3

  • Validating comma-delimited list for numeric entries

    Hi!
    I need to validate a comma-delimited list to make sure all the list items are numeric.  I could do a cfloop to loop through the list, then an IsValid() to check each entry, but that seems cumbersome, so I was wondering if there was a better way.
    Thanks!

    BreakawayPaul wrote:
    I had the idea to just do a replace() to get rid of all the commas and treat the value as one big number.  It seems to work.
    True. That is a creative test. But what if the list begins with 0 or contains negative or decimal numbers?
    If you must include those such eventualities, then you could extend the test to something like
    <cftry>
    <cfset myList="0,1,2,x">
    <cfset maxNo=arrayMax(listToArray(myList))>
    <!--- The rest of the business code goes here --->
    <cfcatch type="expression">
    <cfoutput>#cfcatch.Detail#</cfoutput>
    </cfcatch>
    </cftry>

  • Script to get tab delimited list of folder names within a main directory

    I need a script to create a tab delimited text file of the names of each folder within a specific folder. Haven't found anything...Anybody have an idea how to proceed?
    Muchas gracias!

    Now that I think about this a little more, I'm guessing you want two further pieces of information.
    You don't want just the name of the folders, you want their path, and you want to capture subfolders as well, correct?
    If that's the case, try this:
    tell application "Finder"
      -- get the starting folder
      set topFolder to (choose folder with prompt "Please select the top folder")
      -- get all subfolders
      set subfolders to (every folder of entire contents of topFolder as alias list)
      -- open a file to write the data to
      set myFile to (open for access file (((path to desktop folder) as text) & "folders.txt") with write permission)
      set eof myFile to 0
      -- remember our current TIDs
      set oldTID to my text item delimiters
      -- iterate through the folders
      repeat with eachFolder in subfolders
        -- break the path based on colons
        set my text item delimiters to ":"
        set folderPath to text items of (eachFolder as text)
      -- set the TIDs to a tab
        set my text item delimiters to tab
        - and convert the path to a tab-delimited string
        set tabDelimitedText to folderPath as text
        -- now write that text to the file
        write tabDelimitedText & return to myFile
      end repeat
      -- clean up, restoring TIDs to what they were
      set my text item delimiters to oldTID
      -- and close the file
      close access myFile
    end tell

  • Adding spaces in comma-delimited lists

    I'm pulling from a database comma-delimited db that appears
    like so:
    Carpet,Hardwood,Tile
    How can I add spaces after the comma (if there's commas at
    all)?

    #Replace(yourstringorvar, ",", ", ", "ALL")#
    Azadi Saryev
    Sabai-dee.com
    http://www.sabai-dee.com

  • Selecting from a comm delimited list

    Often we run queries like
    SELECT * FROM TABLENAME WHERE FIELDA NOT IN ('A','B','C');
    But what if your question goes in the opposite direction, what syntax would work?
    In other words. suppose I want to know which values in the list are not in the table. How could I find that out without having to create a temp table?
    I'm thinking that something like the following might work:
    SELECT FIELDA FROM ('A','B','C') A
    WHERE NOT EXISTS (SELECT 1 FROM TABLENAME B
    WHERE B.FIELDA = A.FIELDA)

    If you have a list of 30,000 items that you want to consider, then you'll likely want to have those items in a table. Here I'll create a fake table of orders, then create a shipment for most of those orders. Then I'll ask which orders of order type "PACKAGE BODY" have not been shipped.
    SQL> create table orders as
      2  select object_id AS order_id,
      3         object_type as order_type,
      4         owner as customer
      5    from all_objects;
    Table created.
    SQL>
    SQL> create table shipments as
      2  select *
      3    from orders
      4   where mod(order_id,47) > 0;
    Table created.
    SQL>
    SQL> select order_id
      2    from orders
      3   where order_type = 'PACKAGE BODY'
      4  minus
      5  select order_id
      6    from shipments
      7   where order_type = 'PACKAGE BODY';
      ORDER_ID
          3290
          3619
          3948
          4888
          5499
          5546
         25098
         25192
         29422
         32618
    10 rows selected.
    SQL>

  • Comma delimited lists

    The data is as below:
    create table mylist
    id number,
    list varchar2(50)
    begin
    insert into mylist (id,list) values (111,'1,2');
    insert into mylist (id,list) values (222,'2,3');
    insert into mylist (id) values (333);
    commit;
    end;
    create table mylistvalues
    value number
    begin
    insert into mylistvalues (value) values (1);
    insert into mylistvalues (value) values (2);
    insert into mylistvalues (value) values (3);
    insert into mylistvalues (value) values (4);
    commit;
    end;
    I have to populate all ids in mylist table where list has one valid value in mylistvalues table.
    The output should be 111 and 222, because 1,2,3 are in mylistvalues table.
    Thanks.

    SELECT  DISTINCT id
      FROM  mylist,
            mylistvalues
      where regexp_like(',' || list || ',',',' || value || ',')
            ID
           222
           111
    SQL> SY.

Maybe you are looking for

  • ADFS Web Application Proxy - Automatically authenticate another federation

    I am setting up a Web Application Proxy as a reverse proxy to publish some of our internal websites to the internet. I am going to publish https://portal.workplace.example as the "hub" site which will link off to various other websites hosted interna

  • CAn't sync to iTunes 7.4.1

    I just took delivery of my new (older) iPod 80GB video. Brand new from apple online, and so far I can't get it to sync with any more than 15.75GB of my 40+GB iTunes library. I've followed all the advice on the discussion boards here, and spent 90mins

  • Mp3 wont'play on 6111 - file format not supported

    hi i've just uploaded an mp3 file in the gallery of my 6111 phone. i wanted to use it as ringtone, but when i try to open it, it complains "file format not supported". the manual says my phone can play mp3 and aac, so what kind of mp3 will it play? i

  • Photo Orientation around the Compass

    When upgrading to the 3.0 for the iphone, I noticed when viewing photos, the orientation only works to 3 sides. If you viewing in a landscape mode, I can turn my iphone 180º, the photos will flip to match orientation. When viewing in portrait and tur

  • Vision Builder AI: (Hex 0xFFFA960C) Cannot open the inspection file.

    I hav built an inspection in vision builder for automated inspection (the code , image and inspection is provided in the attachment) but my program is unable to open the inspection it is throwing an error : Error -354804 occurred at VBAI Interface -