Plsql Collections help

Database table has two columns category and products.
Table: catalog
category products
fruit apple
vegetable carrot
soda pepsi
vegetable potato
fruit grapes
fruit orange
vegetable cabbage
soda coke
i need to read the records from table catalog and store them in some sort of plsql collection. I then have to read from that collection and write output as follows:
Note: the categories and products should be sorted alphabetically in output.
OUTPUT
fruit apple, grapes, orange
soda coke, pepsi
vegetable cabbage, carrot, potato
please help me as how this can be done?
Thanks
G

Without collections:
SQL> DECLARE
  2      CURSOR c
  3        IS
  4          WITH t AS (
  5                     SELECT 'fruit' category,'apple' product FROM dual UNION ALL
  6                     SELECT 'vegetable','carrot' FROM dual UNION ALL
  7                     SELECT 'soda','pepsi' FROM dual UNION ALL
  8                     SELECT 'vegetable','potato' FROM dual UNION ALL
  9                     SELECT 'fruit','grapes' FROM dual UNION ALL
10                     SELECT 'fruit','orange' FROM dual UNION ALL
11                     SELECT 'vegetable','cabbage' FROM dual UNION ALL
12                     SELECT 'soda','coke' FROM dual
13                    )
14          SELECT  category,
15                  ltrim(sys_connect_by_path(product,', '),', ') product_list
16            FROM  (
17                   SELECT  category,
18                           product,
19                           row_number() over(partition by category order by product) rn
20                     FROM  t
21                  )
22            WHERE connect_by_isleaf = 1
23            START WITH rn = 1
24            CONNECT BY category = PRIOR category
25                   AND rn = PRIOR rn + 1
26            ORDER BY category;
27  BEGIN
28      FOR v_rec IN c LOOP
29        DBMS_OUTPUT.PUT_LINE(rpad(v_rec.category,10) || v_rec.product_list);
30      END LOOP;
31  END;
32  /
fruit     apple, grapes, orange
soda      coke, pepsi
vegetable cabbage, carrot, potato
PL/SQL procedure successfully completed.
SQL> And in plain SQL:
SQL> COLUMN PRODUCT_LIST FORMAT A50
SQL> WITH t AS (
  2             SELECT 'fruit' category,'apple' product FROM dual UNION ALL
  3             SELECT 'vegetable','carrot' FROM dual UNION ALL
  4             SELECT 'soda','pepsi' FROM dual UNION ALL
  5             SELECT 'vegetable','potato' FROM dual UNION ALL
  6             SELECT 'fruit','grapes' FROM dual UNION ALL
  7             SELECT 'fruit','orange' FROM dual UNION ALL
  8             SELECT 'vegetable','cabbage' FROM dual UNION ALL
  9             SELECT 'soda','coke' FROM dual
10            )
11  SELECT  category,
12          ltrim(sys_connect_by_path(product,', '),', ') product_list
13    FROM  (
14           SELECT  category,
15                   product,
16                   row_number() over(partition by category order by product) rn
17             FROM  t
18          )
19    WHERE connect_by_isleaf = 1
20    START WITH rn = 1
21    CONNECT BY category = PRIOR category
22           AND rn = PRIOR rn + 1
23    ORDER BY category
24  /
CATEGORY  PRODUCT_LIST
fruit     apple, grapes, orange
soda      coke, pepsi
vegetable cabbage, carrot, potato
SQL> SY.

Similar Messages

  • Wat's Plsql collections?

    Can anyone help me about Plsql collections and why we need this?

    Welcome to the forum.
    Your question is quite broad.
    A quick search through the Oracle docs will give you explanations and examples
    http://www.oracle.com/pls/db112/search?remark=quick_search&word=collections
    http://www.oracle.com/pls/db112/homepage
    As well as a search on AskTom, for example:
    http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:3170352229012
    As well as a search on this forum.
    why we need this?It depends. Perhaps you don't need them, perhaps you do.
    Amongst others on your specific requirement and your datamodel.

  • PLSQL COLLECTIONS(10g)

    Hi People,
    I have a clarification in plsql collections.it is defined that plsql collections are used to collect values of same data type.but in 10g document it is told that you can also use INDEX BY tables along with %ROWTYPE.how this is possible?.%ROWTYPE is used to draw different data types.how to use this along with INDEX BY tables. Pls help me with some sample codes.
    with regards
    vids

    vidusnat wrote:
    In the above example plsql table is used with %ROWTYPE It is not a PL/SQL "+table+". There is no such thing. No such concept. It is INCORRECT terminology used by many, including Oracle. (Oracle has however corrected this terminology in recent documentation).
    That type defines an associative array.
    which is used to collect values of different data types.Correct. The +%RowType+ clause saves us time and effort in redefining a PL/SQL record structure that duplicates the structure (SQL projection) of a table, view or cursor.
    So in effect, instead of having to code this, we use +%RowType+ instead.
    declare
      type TEmployeeRecord is record(
        emp_id number,
        surname varchar2(80),
       .. etc ..
      type EmpTabTyp is table of TEmployeeRecord
        index by pls_integer;To manually define a structure like this each time for a table/view/cursor is lots of coding. Easy to get wrong. And if the underlying SQL projection changes, then we need to manually update the structure.
    So +%RowType+ saves us all the extra coding and maintenance of defining a PL/SQL struct that duplicates a SQL projection structure. If you know C/C++, think of it as a compiler macro that defines the relevant struct for you.
    but plsql collections are defined to collect values of same data type.You have not define a collection. A collection is a different type of structure and has different features. You have defined an associative array.
    using %ROWTYPE is contrary to plsql collection's definition.can anyone pls explain me how it is possible?There is no contradiction here. Just confusion it seems?
    A collection is not an associative array. An associative array is not a collection. Both can be based on the same structure. Both can be used to received SQL cursor output. However, there are differences in features - especially how one addresses the contents. In essence, an associative array is addressed via name. Each cell in the array is named - or in the case of the name being a numeric, a number value. The 1st cell in the associative array can be named (or numbered in your case) using "100" - as you did in your sample code. So to address the contents of the 1st cell in that array, you need to reference it by index value 100. Not 1.
    A collection is not addressed via a name of the cell. Instead, it is addressed by location/position of the cell. So the 1st cell will be addressed by 1, the 2nd cell by 2 and so on.

  • How to fetch from cursor into plsql collection

    Dear Friends,
    I am trying to understand PLSQL collections. I am trying with the following example.
    CREATE OR REPLACE TYPE emp_obj AS OBJECT
    (     empname          VARCHAR2(100),     empjob          VARCHAR2(50),     empsal          NUMBER);
    CREATE OR REPLACE TYPE emp_tbl IS TABLE OF emp_obj;
    CREATE OR REPLACE PACKAGE eg_collection AS
    -- Delcare ref cursor
    TYPE rc IS REF CURSOR;
    -- Procedure
    PROCEDURE eg_collection_proc (out_result OUT rc);
    END;
    CREATE OR REPLACE PACKAGE BODY eg_collection AS
    PROCEDURE eg_collection_proc( out_result OUT rc) AS
    emp_tdt     emp_tbl := emp_tbl(emp_obj('oracle','DBA',100));
    CURSOR c2 IS SELECT ename,job,sal FROM emp WHERE sal > 2000;
    -- Declare a record type to hold the records from cursor and then pass to the collection
    emp_rec emp_obj;
    BEGIN
         OPEN c2;
         LOOP FETCH c1 INTO emp_rec;
              EXIT WHEN c1%NOTFOUND;
              emp_tdt.extend;
    emp_tdt(emp_tdt.count) := emp_rec;
         END LOOP;
         CLOSE c2;
    OPEN out_result FOR SELECT * FROM TABLE(CAST(emp_tdt AS emp_tbl));
    END eg_collection_proc;
    END eg_collection;
    Executing the proc
    variable r refcursor;
    exec eg_collection.eg_collection_proc(:r);
    print r;
    But I am getting compilation error type mismatch found at emp_rec between fetch cursor into variable

    I am trying to understand PLSQL collections. I dont why the code is not working
    SQL> CREATE OR REPLACE TYPE emp_obj AS OBJECT
    2 (
    3      empname          VARCHAR2(100),
    4      empjob          VARCHAR2(50),
    5      empsal          NUMBER
    6 )
    7 /
    Type created.
    SQL> CREATE OR REPLACE TYPE emp_tbl IS TABLE OF emp_obj
    2 /
    Type created.
    SQL> DECLARE
    2      emp_tdt emp_tbl := emp_tbl ();
    3 BEGIN
    4
    5      emp_tdt.extend;
    6      SELECT emp_obj(ename, job, sal) BULK COLLECT INTO emp_tdt
    7      FROM emp WHERE sal < 4000;
    8
    9      DBMS_OUTPUT.PUT_LINE ('The total count is ' || emp_tdt.count);
    10
    11      emp_tdt.extend;
    12      SELECT ename, job, sal INTO emp_tdt(1).empname, emp_tdt(1).empjob, emp_tdt(1).empsal
    13      FROM emp WHERE empno = 7900;
    14
    15      DBMS_OUTPUT.PUT_LINE ('The total count is ' || emp_tdt.count);
    16
    17 END;
    18 /
    The total count is 13
    The total count is 14
    PL/SQL procedure successfully completed.
    SQL> DECLARE
    2      emp_tdt emp_tbl := emp_tbl ();
    3 BEGIN
    4
    5      emp_tdt.extend;
    6      SELECT ename, job, sal INTO emp_tdt(1).empname, emp_tdt(1).empjob, emp_tdt(1).empsal
    7      FROM emp WHERE empno = 7900;
    8
    9      DBMS_OUTPUT.PUT_LINE ('The total count is ' || emp_tdt.count);
    10
    11      emp_tdt.extend;
    12      SELECT emp_obj(ename, job, sal) BULK COLLECT INTO emp_tdt
    13      FROM emp WHERE sal < 4000;
    14
    15      DBMS_OUTPUT.PUT_LINE ('The total count is ' || emp_tdt.count);
    16 END;
    17 /
    DECLARE
    ERROR at line 1:
    ORA-06530: Reference to uninitialized composite
    ORA-06512: at line 6

  • Select data from plsql collections

    Hi All,
    I am not a developer but working as a DBA, so not very much familiar with pl/sql, still gone through with documentation and could come up with some solution of my problem. I need some expert advice here.
    Problem : I am writing down some kind of plsql program for monitoring of some special batch job, I know we have lot of other option to do the same including db/grid control ..etc but for some
    reason i have to do this using plsql only.
    Requirement : my requirement is to select data from table in plsql and then should have ability to query it again and again. I would not prefer to go to table rather than directly from plsql..
    I wrote down below code for sample, bulk collect data into collection type and can print using for loop.
    Declare
    type ts is table of v$session%rowtype index by pls_integer;
    tsess ts;
    begin
    select * bulk collect into tsess from v$session ;
    for i in 1..tsess.count loop
    dbms_output.put_line(tsess(i).terminal);
    end loop;
    end;
    But, is there any way same collection ( tsess in above example ) can be queried using select statement like 'select * from table ( Tsess ) ' I have searched on net and found this can be done using creating type at database level. But my problem is I can not create any object in database as being it is a production one.
    I was looking for if is there any way same can be accomplished ... like cast / multiset .. however, I could not get it through.
    your help would be appreciated !!
    Regards,

    I don't think you need to use arrays here, only SQL, have a look at subquery factors and report back if that is insufficient...
    Edited by: BrendanP on 12-Feb-2012 03:07 to add an example:
    I gather that you want to 'requery' data that you have already got from the database purely to be able to use SQL functionality such as ORDER BY in multiple ways. Here is how you can do this in the original SQL for one particular example, where you want to query v$sql ordering by CPU time and by disk reads separately (I tested this but the output won't look good here, so omitting it):
    WITH v AS (
    SELECT
        Substr (sql_text,1,500)             sql_text,
        cpu_time/1000000                    cpu_seconds,
        disk_reads,
        buffer_gets,
        executions,
        CASE WHEN rows_processed != 0 THEN Round( buffer_gets / Nvl (Replace (rows_processed, 0, 1) ,1)) END Buffer_gets_rows_proc,
        Round (buffer_gets / Nvl (Replace (executions, 0, 1), 1)) Buffer_gets_executions,
        elapsed_time / 1000000              elapsed_second,
        module
    FROM v$sql s)
    SELECT
        'CPU'                order_by,
        cpu_seconds          order_val,
        sql_text,
        cpu_seconds,
        disk_reads,
        buffer_gets,
        executions,
        buffer_gets_rows_proc,
        buffer_gets_executions,
        elapsed_second,
        module
    FROM v
    UNION
    SELECT
        'Disk reads',
        disk_reads,
        sql_text,
        cpu_seconds,
        disk_reads,
        buffer_gets,
        executions,
        buffer_gets_rows_proc,
        buffer_gets_executions,
        elapsed_second,
        module
    FROM v
    ORDER BY order_by, order_val DESC

  • Urgent - How to call a Web Services from PLSQL - Please help

    Hello,
    I am very much new to WebServices, need to call web services through PLSQL. I have a urgent requirement, where i need to call the web services by passing from some paramters to it and the web services will return a varchar values as 'PASSED' or 'FAILED'.
    Can you please approch me the best way to start with.
    Thanks,
    Srikanth.

    Hi,
    I need to do it from PLSQL API's not from JAVA.
    I have started developing the code through UTIL_HTTP. Getting lots of error.
    Can you please guide me through these error.
    Below is the wsdl and a blcok where i am trying to retrive the value from webservice.
    Hope this will help you.
    Code:
    declare
    soap_request varchar2(30000);
    soap_respond varchar2(30000);
    http_req utl_http.req;
    http_resp utl_http.resp;
    resp XMLType;
    i integer;
    begin
    soap_request:= '<?xml version = "1.0" encoding = "UTF-8"?>
    <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <SOAP-ENV:Body>
    <ns1:soapCheckRequest1 wsdl:ns1="https://isportal-qa.iss.net/exportcompliancemanager/services/ExportCheckService" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
    <FirstName xsi:type="xsd:string">saddam</FirstName>
    <LastName xsi:type="xsd:string">hussein</LastName>
              <companyName xsi:type="xsd:string">samueladams</companyName>
              <address1 xsi:type="xsd:string">123 APT</address1>
              <address3 xsi:type="xsd:string">Atlanta</address3>
              <city xsi:type="xsd:string">uk</city>
              <stateOrRegion xsi:type="xsd:string">GA</stateOrRegion>
              <postalCode xsi:type="xsd:string">30338</postalCode>
              <email xsi:type="xsd:string">sj@samueladams</email>
              <isoCountryCode xsi:type="xsd:string">US</isoCountryCode>
              <endUserIP xsi:type="xsd:string">209.134.168.203</endUserIP>
    </ns1:soapCheckRequest1>
    </SOAP-ENV:Body>
    </SOAP-ENV:Envelope>
    http_req:= utl_http.begin_request
    ( 'http://isportal-qa.iss.net/exportcompliancemanager/services/ExportCheckService'
    , 'POST'
    , 'HTTP/1.1'
    utl_http.set_header(http_req, 'Content-Type', 'text/xml'); -- since we are dealing with plain text in XML documents
    utl_http.set_header(http_req, 'Content-Length', length(soap_request));
    utl_http.set_header(http_req, 'SOAPAction', ''); -- required to specify this is a SOAP communication
    utl_http.write_text(http_req, soap_request);
    http_resp:= utl_http.get_response(http_req);
    DBMS_OUTPUT.PUT_LINE('-------utl_http.get_response---------------------');
    DBMS_OUTPUT.PUT_LINE('http_resp.status_code is :'||http_resp.status_code );
    DBMS_OUTPUT.PUT_LINE('http_resp.reason_phrase is :'||http_resp.reason_phrase);
    DBMS_OUTPUT.PUT_LINE('http_resp.http_version is :'||http_resp.http_version);
    DBMS_OUTPUT.PUT_LINE('http_resp.private_hndl is :'||http_resp.private_hndl);
    DBMS_OUTPUT.PUT_LINE('-------utl_http.get_response----------------------');
    utl_http.read_text(http_resp, soap_respond);
    utl_http.end_response(http_resp);
    resp:= XMLType.createXML(soap_respond);
    resp:= resp.extract('/soap:Envelop/soap:Body/child::node()'
    , 'xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"'
    i:=0;
    loop
    dbms_output.put_line(substr(soap_respond,1+ i*255,250));
    i:= i+1;
    if i*250> length(soap_respond)
    then
    exit;
    end if;
    end loop;
    end;
    Error Message
    http_resp.reason_phrase is :Internal Server Error
    http_resp.http_version is :HTTP/1.1
    http_resp.private_hndl is :0
    -------utl_http.get_response----------------------
    <?xml version="1.0" encoding="UTF-8"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soapenv:Body><soapenv:Fault><faultco
    apenv:Server.userException</faultcode><faultstring>org.xml.sax.SAXParseException: The prefix &quot;ns1&quot; for element &quot;ns1:soapCheckRequest1&quot; is not bound.</faultstring><detail><ns1:hostname xmlns:ns1="http://xml.apache.org/axis/">atlcms
    2.iss.net</ns1:hostname></detail></soapenv:Fault></soapenv:Body></soapenv:Envelope>
    <?xml version="1.0" encoding="UTF-8" ?>
    - <wsdl:definitions targetNamespace="https://isportal-qa.iss.net/exportcompliancemanager/services/ExportCheckService" xmlns:apachesoap="http://xml.apache.org/xml-soap" xmlns:impl="https://isportal-qa.iss.net/exportcompliancemanager/services/ExportCheckService" xmlns:intf="https://isportal-qa.iss.net/exportcompliancemanager/services/ExportCheckService" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:wsdlsoap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    - <!--
    WSDL created by Apache Axis version: 1.3
    Built on Oct 05, 2005 (05:23:37 EDT)
    -->
    - <wsdl:message name="soapCheckResponse1">
    <wsdl:part name="soapCheckReturn" type="soapenc:string" />
    </wsdl:message>
    - <wsdl:message name="soapCheckRequest1">
    <wsdl:part name="firstName" type="soapenc:string" />
    <wsdl:part name="lastName" type="soapenc:string" />
    <wsdl:part name="companyName" type="soapenc:string" />
    <wsdl:part name="address1" type="soapenc:string" />
    <wsdl:part name="address2" type="soapenc:string" />
    <wsdl:part name="address3" type="soapenc:string" />
    <wsdl:part name="city" type="soapenc:string" />
    <wsdl:part name="stateOrRegion" type="soapenc:string" />
    <wsdl:part name="postalCode" type="soapenc:string" />
    <wsdl:part name="email" type="soapenc:string" />
    <wsdl:part name="phone" type="soapenc:string" />
    <wsdl:part name="isoCountryCode" type="soapenc:string" />
    <wsdl:part name="endUserId" type="soapenc:string" />
    <wsdl:part name="endUserIP" type="soapenc:string" />
    <wsdl:part name="endUserSession" type="soapenc:string" />
    <wsdl:part name="performGovCheck" type="xsd:boolean" />
    <wsdl:part name="sendEmailNotification" type="xsd:boolean" />
    <wsdl:part name="screeningLevelBasedOnSuppliedCountryCode" type="xsd:boolean" />
    <wsdl:part name="screeningLevelBasedOnEndUserIP" type="xsd:boolean" />
    <wsdl:part name="soundexMatch" type="xsd:boolean" />
    </wsdl:message>
    - <wsdl:message name="soapCheckRequest">
    <wsdl:part name="firstName" type="soapenc:string" />
    <wsdl:part name="lastName" type="soapenc:string" />
    <wsdl:part name="companyName" type="soapenc:string" />
    <wsdl:part name="address1" type="soapenc:string" />
    <wsdl:part name="address2" type="soapenc:string" />
    <wsdl:part name="address3" type="soapenc:string" />
    <wsdl:part name="city" type="soapenc:string" />
    <wsdl:part name="stateOrRegion" type="soapenc:string" />
    <wsdl:part name="postalCode" type="soapenc:string" />
    <wsdl:part name="email" type="soapenc:string" />
    <wsdl:part name="phone" type="soapenc:string" />
    <wsdl:part name="isoCountryCode" type="soapenc:string" />
    <wsdl:part name="endUserId" type="soapenc:string" />
    <wsdl:part name="endUserIP" type="soapenc:string" />
    <wsdl:part name="endUserSession" type="soapenc:string" />
    <wsdl:part name="performGovCheck" type="xsd:boolean" />
    <wsdl:part name="sendEmailNotification" type="xsd:boolean" />
    <wsdl:part name="screeningLevelBasedOnEndUserIP" type="xsd:boolean" />
    <wsdl:part name="soundexMatch" type="xsd:boolean" />
    </wsdl:message>
    - <wsdl:message name="soapCheckResponse">
    Thanks and Regard,
    Srikanth

  • LR2 lost all Collections - help please

    I've been working with the upgraded LR2 for a couple of days. Today I was working with Smart Collections, somehow managed to generate an error message (can't remember the wording, sorry), and now I have lost all Collections, both those that were brought across from LR1 and the new ones created today in LR2. The Collections tab is completely empty.
    Restarted LR2 and tried to generate a new Smart Collection, with a title the same as that created before the error. LR2 tells me that the specified name is already in use, so I presume the Collections are on my hard drive somewhere. I'm just searching now for .lrsmcoll
    Is it possible to import previously created Collections, and if so how? I backed up the catalogue this morning - hopefully that has saved me a lot of work :)
    Many thanks for any help
    Mike

    Update: My problem seems to have been self-caused. About the same time I started using LR2 I bought a new hard drive and moved all my pictures to it using a somewhat different directory structure. I was able to "teach" LR2 the new locations but the information in the collections was not updated. I still have the original drive and structure and if that's on-line, the collections work fine. I have found no-way to update the collections as to the new locations. Is there a way?

  • Plsql collections

    Hi,
    I am working with oracle 10g.
    Still i was not familiar with PLSQL Tables or collections.
    Please send me the link or any notes regarding PLSQL Tables.
    Thanks and Regards,
    Ansaf.

    Ansaf wrote:
    Hi,
    I am working with oracle 10g.
    Still i was not familiar with PLSQL Tables or collections.
    Please send me the link or any notes regarding PLSQL Tables.
    Thanks and Regards,
    Ansaf.when all else fail Read The Fine Manual
    http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/collections.htm#sthref1031

  • Simple PHP and PLSQL Bind help needed

    HI,
    I am learning php and oracle I am trying to bind my plsql code with php but have little idea can anyone plese help?.
    my code is
    plsql prcoedure
    CREATE OR REPLACE PROCEDURE get_width (
    img_id IN arm_photos.id%TYPE
    AS
    image ORDSYS.ORDImage;
    width INTEGER;
    BEGIN
    SELECT p.image INTO image FROM arm_photos p
    WHERE p.id = img_id;
    -- Get the image width:
    width := image.getWidth();
    DBMS_OUTPUT.PUT_LINE('Width is ' || width);
    COMMIT;
    END;
    PHP code
    <?php
    $c =oci_connect('user', 'pass' , '//localhost/orcl');
    $s = oci_parse($c, " begin
    get_width(:id :width)");
    oci_bind_by_name($s, ':id', $id);
    oci_bind_by_name($s, ':width', $width);
    $id= 1235;
    oci_execute($s);
    ?>

    Variable width is a local variable. You can't get its value from outside SP. Either change your procedure to a function returning image width or add a second out parameter:
    CREATE OR REPLACE PROCEDURE get_width (
    img_id IN arm_photos.id%TYPE,width OUT INTEGER
    AS
    image ORDSYS.ORDImage;
    BEGIN
    SELECT p.image INTO image FROM arm_photos p
    WHERE p.id = img_id;
    -- Get the image width:
    width := image.getWidth();
    DBMS_OUTPUT.PUT_LINE('Width is ' || width);
    COMMIT;
    END;SY.

  • Plsql cursor help

    i was writing a plsql block using cursors.
    the main theme is that is have a table circle(radius, area) and i just wanted to get the sum of the areas in the table "in the traditional way using a while loop but i get errors like"
    declare
    sum number(6,2) :=0;
    area circle.area%type;
    cursor selector is select area from circle;
    begin
    open selector;
    if selector%isopen then
    while selector%found
    loop
    fetch selector into area;
    sum := sum+area;
    end loop;
    dbms_output.put_line(area);
    close selector;
    else
    dbms_output.put_line('error opening cursor');
    end if;
    end;
    the errors that come up are
    that sum :=sum+area .. error at '+' expecting (
    and several others .. can anyone help me
    i know i can use the sum aggregate function to get the sum.. but i am practicing plsql...

    Hmm. I disagree in part, in that it's useful to know that these methods exist and how they work. I agree that you need to know where and when is best to use (and conversely, not use!) them.
    I've learnt about While loops, for example, and could code one if I had to, but I think I've used it at most once, if at all. Still, I know that it's there should I need it.
    Perhaps the OP could have used a better example to practise on, but I think they'll learn from it none-the-less; if only that it's not a commonly used technique, and that SQL would be much better suited to the task! *{;-)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Garbage Collection Help

    My understanding of garbage collection is that resources utilized by an object are released when no reference to the object exist. I accomplish this by ensuring that all references to an unneeded object are null.
    My question/concern is this. If I have an object "A" that has references to other objects "B", "C", and "D", will the all objects be elibible for garbage collection when the reference to object A is set to null? I suspect that objects "B", "C", and "D" persist until the virtual machine is terminated.
    Is the practice of creating a method within a class to make all inner objects eligible for garbage collection prior to setting the object reference to null. (i.e. set objects "B", "C", and "D" to null prior to setting "A" to null).
    Maybe I am just paranoid??

    My understanding of garbage collection is that
    resources utilized by an object are released when no
    reference to the object existThat's not correct. Objects can have references that point to them and still be garbage collected. For example:
    Vector v = new Vector();
    v.add(new Object());
    v = null;
    After this code is executed, the Vector object has a reference to the "new Object()" created. However, the Vector itself is not reachable, and therefore the "new Object()" is unreachable, and therefore both are collected.
    The garbage collector collects unreachable objects.
    I accomplish this by
    ensuring that all references to an unneeded object are
    null.It is quite rare that setting a reference to null is needed to make an object unreachable. Don't do it -- it makes your code slower, less readable, and harder to modify.
    My question/concern is this. If I have an object "A"
    that has references to other objects "B", "C", and
    "D", will the all objects be elibible for garbage
    collection when the reference to object A is set to
    null? I suspect that objects "B", "C", and "D"
    persist until the virtual machine is terminated.Yes -- all will be collected when A becomes unreachable. As noted earlier, you shouldn't need to set any reference to null for this to happen.
    Is the practice of creating a method within a class to
    make all inner objects eligible for garbage collection
    prior to setting the object reference to null. (i.e.
    set objects "B", "C", and "D" to null prior to setting
    "A" to null).
    Maybe I am just paranoid??Yes. Just let the garbage collector do its job and collect unreachable objects. You should almost never need to write any code to "help" the garbage collector.

  • Plsql Code Help

    Hi everyone,
    I am sorry for what all mistakes I have done earlier. As, I am a new member, I didn't learn all the FAQ in OTN. But now, I read all the FAQ's developed by Blueshadow and I need anyone to help me modifying the code for my new business rule. Once again I am sorry to Venkadesh, ACE, Gary, Etbin and Blueshadow for all my mistakes.
    Sara Dee

    CN_DEFAULT_LANGUAGE_ID     cad_languages.language_id%type default toe$translate.fn_get_language_id;
    GKV_SLI_SITE_CHAMP_URL  constant    cad_parameters.text_value%type default cad$param.get_parameter_text_value('TUP_SLI_SITE_CHAMP_URL',GCN_DEFAULT_COMPANY_ID);
    GKV_SLI_SEARCH_COUNT    constant    cad_parameters.number_value%type default cad$param.get_parameter_number_value('TUP_SLI_SEARCH_COUNT',GCN_DEFAULT_COMPANY_ID);
    GKV_SLI_XML_PATH        constant    cad_parameters.text_value%type default cad$param.get_parameter_text_value('TUP_SLI_XML_PATH',GCN_DEFAULT_COMPANY_ID);
    GKV_SLI_XML_NODE1_NAME  constant    cad_parameters.text_value%type default cad$param.get_parameter_text_value('TUP_SLI_XML_NODE1_NAME',GCN_DEFAULT_COMPANY_ID);
    GKV_SLI_XML_NODE2_NAME  constant    cad_parameters.text_value%type default cad$param.get_parameter_text_value('TUP_SLI_XML_NODE2_NAME',GCN_DEFAULT_COMPANY_ID);
    gv_ip_redirect_url                  varchar2(1000);
    gv_refer_url                        varchar2(1000);
    gv_sli_search_url                   varchar2(1000);
    gv_page_ref_url                     varchar2(1000);
    gv_procedure_name                   varchar2(100);
    gv_item_number                      varchar2(30);
    gv_category_code                    varchar2(30);
    gv_category_page_num                varchar2(3);
    gv_section                          varchar2(30);
    gv_user                             varchar2(30);
    gv_lang                             varchar2(30);
    gv_gift_code                        varchar2(30);
    gv_fname                            varchar2(50);
    gv_lname                            varchar2(50);
    gv_email                            varchar2(100);
    gv_message                          varchar2(2000);
    gv_face_amount                      tup_gift_certificates.face_value_amount%type;
    gv_error_message                    varchar2(2000);
    gv_def_category                     varchar2(30)    := null;
    gv_categ_description                varchar2(1000);
    gn_company_id                       number          default cad$user_api.get_user_company_id;
    gn_language_id                      number          default toe$translate.fn_get_language_id;
    gn_script_id                        number          := -1;
    gn_retail_price_list_id             number          := coe$item.get_event_price_list_id;
    gn_gift_certificate                 number;
    gn_page_number                      number;
    gn_page_count                       number;
    gn_order_id                         number;
    gn_start_price                      number;
    gn_end_price                        number;
    gi_heading_index                    binary_integer;
    gn_total_items                      number  := 0;
    gkn_page_item_max       constant    number  := 14;
    gkn_items_per_row       constant    number  := 7;
    gb_gifts_found                      boolean := false;
    gb_pk_details_found                 boolean := false;
    gb_show_pdc                         boolean := false;
    gb_show_item_photo                  boolean := false;
    gb_show_item_host                   boolean := false;
    ge_ip_address_restricted            exception;
    ge_no_parent_item                   exception;
    gcv_registry                        varchar2(30) default common_global.f_get_cookie_value('registry');
    gcv_registry_status                 varchar2(30) default common_global.f_get_cookie_value('registry_status');
    gcv_highlight_class                 varchar2(50) default common_defaults.f_get_class_name('highlight',gcv_registry_status);
    gcv_hyp_color_class                 varchar2(50) default common_defaults.f_get_class_name('hyp_color',gcv_registry_status);
    gcv_headline_class                  varchar2(50) default common_defaults.f_get_class_name('headline',gcv_registry_status);
    gcv_form_class                      varchar2(50) default common_defaults.f_get_class_name('form',gcv_registry_status);
    cursor gcr_item_data ( cfv_item_category_code        varchar2,
                            cpn_script_id           number,
                            cpn_relship_type_id     number)
    is
        select  /*+ ordered use_nl( cic, cicm, cmi) */
                cicm.sort_order,
                cmi.item_number master_item_number,
                cmi.small_image_description detail,
                cmi.image_filename image_filename,
                cmi.long_description long_description,
                cmi.short_description short_desc,
                cmi.small_image_filename small_image_filename,
                cmi.numeric_item_number,
                1   relationship_type
        from    coe_item_categories cic,
                coe_item_category_mappings cicm,
                coe_master_items cmi
        where   sysdate between nvl (cmi.start_date, sysdate - 1) and nvl (cmi.end_date, sysdate + 1)
        and     cmi.inactive_flag = 0
        and     exists (select 'x'
                        from    coe_item_relationships cir,
                                coe_event_item_prices eip
                        where   cir.parent_master_item_id   = cmi.master_item_id
                        and     cir.child_master_item_id    = eip.master_item_id
                        and     cir.company_id = eip.company_id+0
                        and     eip.event_price_list_id+0 = gn_retail_price_list_id
                        and     eip.inactive_flag = 0
                        and     sysdate between eip.start_time_date and nvl(eip.end_time_date, sysdate)
                        and     cir.item_relationship_type_id+0 = cpn_relship_type_id
                        and     cir.inactive_flag = 0
                        and     sysdate between nvl (cir.start_time_date, sysdate - 1) and nvl(cir.end_time_date, sysdate + 1)  --TSR 32282  
                        --and     cir.company_id+0 = gn_company_id
        and     cmi.master_item_id = cicm.master_item_id
        and     nvl(cicm.script_id, cpn_script_id) = cpn_script_id
        and     (sysdate) between nvl (cicm.start_time_date, sysdate - 1) and nvl (cicm.end_time_date, sysdate + 1)
        and     cicm.inactive_flag = 0
        and     cic.item_category_code = cicm.item_category_code
        and     cic.display_heading_flag = 1
        and     cic.item_category_code = cfv_item_category_code
        union all
        select  /*+ ordered use_nl( cic, cicm, cmi) */
                cicm.sort_order,
                cmi.item_number master_item_number,
                cmi.small_image_description detail,
                cmi.image_filename image_filename,
                cmi.long_description long_description,
                cmi.short_description short_desc,
                cmi.small_image_filename small_image_filename,
                cmi.numeric_item_number,
                0   relationship_type
        from    coe_item_categories cic,
                coe_item_category_mappings cicm,
                coe_master_items cmi
        where   sysdate between nvl (cmi.start_date, sysdate - 1) and nvl (cmi.end_date, sysdate + 1)
        and     cmi.inactive_flag = 0
        and     exists (select  'x'
                        from    coe_event_item_prices eip
                        where   cmi.master_item_id = eip.master_item_id
                        and     eip.event_price_list_id+0 = gn_retail_price_list_id
                        and     eip.inactive_flag = 0
                        and     sysdate between eip.start_time_date and eip.end_time_date
        and     cmi.master_item_id = cicm.master_item_id
        and     nvl(cicm.script_id, cpn_script_id) = cpn_script_id
        and     sysdate between nvl (cicm.start_time_date, sysdate - 1) and nvl (cicm.end_time_date, sysdate + 1)
        and     cicm.inactive_flag = 0
        and     cic.item_category_code = cicm.item_category_code
        and     cic.display_heading_flag = 1
        and     cic.item_category_code = cfv_item_category_code
        order by 1, 2;

  • PLSQL Collections and record types

    Hi,
    I'm trying to use collection in my code in 10g database
    declare
    cursor c_cur
    is
    select  * from table;
    TYPE tbl_cur_lines IS TABLE OF c_cur%ROWTYPE
          INDEX BY BINARY_INTEGER;
          l_cur_rec    tbl_cur_lines;
    begin
    OPEN c_cur;
    FETCH c_cur BULK COLLECT INTO l_cur_rec;
    CLOSE c_open_trx;                       
    FOR i IN 0..l_cur_rec.COUNT-1
    LOOP
              --  do something
    END LOOP;
    end;if i use count for number of records its working
    declare
    cursor c_cur
    is
    select  * from table;
    TYPE tbl_cur_lines IS TABLE OF c_cur%ROWTYPE
          INDEX BY BINARY_INTEGER;
          l_cur_rec    tbl_cur_lines;
    begin
    OPEN c_cur;
    FETCH c_cur BULK COLLECT INTO l_cur_rec;
    CLOSE c_open_trx;                       
    FOR i IN l_cur_rec.FIRST..l_cur_rec.LAST
    LOOP
              --  do something
    END LOOP;
    end;If i use above code i'm getting following error
    ORA-06502: PL/SQL: numeric or value error
    Can some explain difference...
    Thanks in advance!
    Edited by: user641008 on Jun 3, 2011 2:31 PM

    FOR i IN 0..l_cur_rec.COUNT-1
    here, index "i" expect an integer value and it is getting and integer, hence not
    giving an error, though your cursor did not fetch any row.
    in the next case,
    FOR i IN l_cur_rec.FIRST..l_cur_rec.LAST
    your cursor did not fetch any row and hence
    first element in your collection is NULL( in other words, there is no index value in collection) while "i" is expecting an integer,
    thats why you are getting error "ORA-06502: PL/SQL: numeric or value error"
    It is always good practice, check collection count before actually processing by loop.
    Change as follows
    declare
    cursor c_cur
    is
    select  * from table;
    TYPE tbl_cur_lines IS TABLE OF c_cur%ROWTYPE
          INDEX BY BINARY_INTEGER;
          l_cur_rec    tbl_cur_lines;
    begin
    OPEN c_cur;
    FETCH c_cur BULK COLLECT INTO l_cur_rec;
    CLOSE c_cur;                       
    if  l_cur_rec.count>0 then      -- Add condition here
    FOR i IN l_cur_rec.FIRST..l_cur_rec.LAST
    LOOP
              --  do something
    END LOOP;
    end if;
    end;

  • Adobe Creative Suite Master Collection Help

    Hey all,
    This is the problem. Basically, my brother finished University last year. He moves out and takes all his stuff with him. A year passes and now it's my time for the great adventure. I have chosen to follow in his path and take Motion Graphics and Cinematography.
    I recently hand built a computer from scratch. He gave me his old Adobe Creative Suite 5.5 Master Collection which is the Student and Teacher edition. He has completely uninstalled and removed all serial codes on his machine. Can I simply now install it on my machine and just apply for a student code via the way I was told (email support)?
    Let me know, would save me a quite a bit of money and I can start learning early.
    Thanks.

    Although Adobe offers a license transfer process, it only applies to the current version which is CS6.
    So I suspect it will not apply to CS5.5.
    Have you tried installing the software and entering the serial number he received?

  • Collection help

    I have a timecard application where I use a header and some collection regions to capture employee data. I have the header working just fine as well as the first collection region, but I can't seem to get the second collection region to update properly. It keeps coming up with a no data found error.
    Processes: On Load: create_or_truncate collection, pre-populate with 3 rows.
    (region display) uses APEX_ITEM and explicitly numbered cells.
    On Submit (Before Computations) - this throws the error
    declare
    cnt NUMBER;
    k pls_integer := 0;
    begin
    select count(seq_id) into cnt from APEX_COLLECTIONS
    where collection_name = 'TC_OTHR_DTL';
    for c2 in (
    select seq_id from APEX_COLLECTIONS
    where collection_name = 'TC_OTHR_DTL'
    order by seq_id) loop
    k := k+1;
    --PAY_CODE
    apex_collection.update_member_attribute (p_collection_name=> 'TC_OTHR_DTL',
    p_seq=> c2.seq_id,p_attr_number =>3,p_attr_value=>wwv_flow.g_f30(k));
    --JOB_CODE
    apex_collection.update_member_attribute (p_collection_name=> 'TC_OTHR_DTL',
    p_seq=> c2.seq_id,p_attr_number =>4,p_attr_value=>wwv_flow.g_f31(k));
    --TASK_HOURS
    apex_collection.update_member_attribute (p_collection_name=> 'TC_OTHR_DTL',
    p_seq=> c2.seq_id,p_attr_number =>5,p_attr_value=>wwv_flow.g_f32(k));
    --LOCATION
    apex_collection.update_member_attribute (p_collection_name=> 'TC_OTHR_DTL',
    p_seq=> c2.seq_id,p_attr_number =>6,p_attr_value=>wwv_flow.g_f33(k));
    --Comments
    apex_collection.update_member_attribute (p_collection_name=> 'TC_OTHR_DTL',
    p_seq=> c2.seq_id,p_attr_number =>7,p_attr_value=>wwv_flow.g_f34(k));
    --Job Start Time
    apex_collection.update_member_attribute (p_collection_name=> 'TC_OTHR_DTL',
    p_seq=> c2.seq_id,p_attr_number =>8,p_attr_value=>wwv_flow.g_f35(k));
    --Job End Time
    apex_collection.update_member_attribute (p_collection_name=> 'TC_OTHR_DTL',
    p_seq=> c2.seq_id,p_attr_number =>9,p_attr_value=>wwv_flow.g_f36(k));
    end loop;
    exception
    when no_data_found then
    apex_application.g_print_success_message := 'Error: ' || cnt || ' records found!';
    when others then
    apex_application.g_print_success_message := 'Unexpected Error';
    end;
    On Submit (After Validations) : Write records to DB.
    Before putting in the error handling, I would just get 01403: No Data Found. After putting in the exception handling, it will process the first row (I see the results on a debug screen that shows all rows from APEX_COLLECTIONS) then die with 'Error: 3 records found.'
    The processes handling the other three collection regions are nearly identical and all function fine. Any ideas?

    The logic was separated into different processes for debugging/development and because it makes sense. For brevity sake, I didn't include all the code, but here is a more detailed overview of what is going on.
    1. I pre-populate several items in the collections based on login information. This includes the ability to pre-load commonly used work items in the collections. The goal is to make data entry as fast as possible given that a clerk can have >200 timecards to process in a day. I didn't mention it, but there is a button on each collection region that adds a row to the collection in case they need more rows than in the default population.
    2. There are different collections because each collection revolves around a given type of work and each type of work has different processing rules requiring different pieces of information. The old application had about 12 columns of which only 3-4 were used on a given row and I was trying to eliminate that. In the old application (based on a flat-file DB), every row was processed based on the data with no thought to separation based on purpose. We separated the data into four tables so we could apply uniform rules based on business process to every row in the table rather than have to create an incredibly complex catch-all processing procedure.
    3. You are correct in that ultimately, I am inserting rows into a table. The only detailed/documented examples I could find for processing collections involved looping through the records.
    4. Nothing actually exists as database records until all the data has been collected. This is to allow page validations to enforce the business rules on each line in each collection, as well as the header. I write the header into one table, and the detail lines in up to 4 more tables depending on whether or not there is any data to record. I tried to enforce many of these with select lists, but this idea was overridden. As a result, all fields are simple text fields.
    5. I have to control the update processes; though I pre-populate many of the records, the data-entry may not require the use of that record. I don't want to store records that aren't useful, so I weed them out as I process the DB write. An MRU is not that flexible.
    6. Most of my code is an adaptation of other collection-handling code I have seen in examples. Any looping, sorting, etc. that was done there was duplicated in my code because it worked. You may advocate other methods, but if so, I need detailed documentation (line-by-line) that explains how it works. I can't look at a piece of code and automatically know how each piece works and why. I wasn't gifted with that ability, so I hope you will forgive me if I stress the need for comments and documentation.
    Of the things I could understand from your example, it appears that one can update each member in a collection row at once without making multiple calls to update_member_attribute. I wasn't aware of that but will allow me to simplify my code tremendously. Thanks.
    The question still remains, however, why I am getting an error message saying that no records exist yet returns 3 rows.

Maybe you are looking for

  • Table of Contents / Bookmarks Jump to Middle of Page Instead of Heading

    I generated a Table of Contents in InDesign, but when I export to the PDF and click on either the actual text link in the table of contents or on the bookmark in the lefthand column, it jumps to the middle of the page that the article is on instead o

  • One apex application, multiple different users

    Hi all, I'm developing an application that will be used by multiple different companies, all with their own data. As far as I can see, there are three different approaches for this: - make different applications with different schemas in apex, for ea

  • Can't paste lyrics into Itunes 10

    I have recently tried to add lyrics to some of my new songs in iTunes 10 (10.0) and when i "right" click (two fingers) in the area to paste lyrics, absolutely nothing happens. My right click does work in all other applications and also in other parts

  • Change log for software updates

    Hello, Given the speed at which software updates come out it would be nice to have a change log to refer to. Thank you,

  • How to delete incorrect entries Mavericks

    DH accidentally typed an incorrect username on a webpage.  Now everytime I start to type the correct username the incorrect one (with the same first two letters) pops up in a box underneath, along with the correct one. How can I delete the incorrect