How to write a procedure to retrieve data in a collection from a table?

create or replace type Subject as object(
subject_id number,
subject_Desc varchar2(50)
create or replace type Subjects_All as varray(10) of Subject
create table student(
StudentID varchar(10),
Subjects Subjects_all
so how do i write a procedure to display info such as this:
Subjects:
101 'Maths'
102 'Science'
Subjects:
I wrote a procedure like the following but it didn't quite work :(
CREATE OR REPLACE PROCEDURE StudentLoop AS
all_subj subjects_all;
each_subj subject;
CURSOR all_subjectsrow IS select * from student;
BEGIN
FOR all_subj IN all_subjectsrow LOOP
FOR each_subj IN all_subj LOOP
DBMS_OUTPUT.PUT_LINE('Last row selected has ID ' || each_subj.subject_id || each_subj.subject_desc );
END LOOP;
END LOOP;
END StudentLoop ;
Any Advice?

Hello,
1.) Don't store Types in Tables. It will become a nightmare when you want to query your data any other way then retrieving your object types. Just don't do it.
2.) A more relational model is much easier. Considering students and subjects is a n:n relation (a student can have more subjects and a subject can have more students) this might look like this:
SQL> r
  1  declare
  2    cursor cStudents is
  3      with student as (
  4        select 1 student_id, 'test1' name from dual
  5        union all
  6        select 2 student_id, 'test2' name from dual
  7      ),
  8      subjects as (
  9        select 1 subject_id, 'Maths' subject_desc from dual
10        union all
11        select 2 subject_id, 'Science' subject_desc from dual
12      ),
13      student_subjects as (
14        select 1 student_id, 1 subject_id from dual
15        union all
16        select 1 student_id, 2 subject_id from dual
17        union all
18        select 2 student_id, 2 subject_id from dual
19      )
20      select a.name name, b.subject_desc subject
21      from student a, subjects b, student_subjects c
22      where a.student_id = c.student_id
23      and b.subject_id = c.subject_id;
24  begin
25    for rS in cStudents loop
26      dbms_output.put_line('Student '||rS.name||': '||rS.subject);
27    end loop;
28* end;
Student test1: Maths
Student test2: Science
Student test1: Sciencecheers

Similar Messages

  • How to write stored procedure to spool data into file

    Hi ,
    We get differnt excel sheets of differnt products.
    We upload data from excel sheet to database . After uploading data , I run Preprossor (sql script) to check the data
    This preprocessor script contains several select statements that query different tables in database .the output is spooled into a cvs file .
    I need to change this script into a stored procedure and spool the output to cvs file.
    File spooling should be done inside the stored procedure so that if I call this stored procedure from java program ,or any concurrent program,its output is .cvs file and in parameter should be productname.
    But inside the stored procedure , we cannot spool the data to some .cvs file . Is any way.I do not want to spool to file when calling.It should be inside stored procedure.
    Or do I need to create a table and insert all the select statements output into it .
    Here is the sample preprocessor script.
    spool Graco_Product.csv
    set head off
    set feedback off
    set Pagesize 100
    SELECT '1. EVERY ASSEMBLY GROUP ADDED IN sys_PRODUCT TABLE MUST HAVE AT LEAST ONE ITEM IN WOC_ASSEMBLY_ITEM'
         FROM DUAL;
    SELECT 'ASSEMBLY_GROUP_NAME'
         FROM DUAL;
    SELECT
         assembly_group_name
         FROM association
         WHERE product_model_name = 'Graco_Product'
         AND assembly_group_name NOT IN (SELECT DISTINCT assembly_group_name FROM woc_assembly_item);
    SELECT '2. A RULE SHOULD HAVE AT LEAST ONE EXPRESSION FOR ITS ACTION SIDE.'
         FROM DUAL;
    SELECT 'RELATION_ID , RELATION_TYPE'
         FROM DUAL;
    SELECT wr.Relation_ID                    ||','||
         wr.Relation_Type                    
         FROM WOC_Relation wr
         WHERE NOT EXISTS (SELECT 'X' FROM WOC_Relation_Expression wre
    WHERE wre.Relation_Side = 'Action'
    AND wr.Relation_ID = wre.Relation_ID)
         AND wr.Relation_Type NOT IN ( 'Rule Warning','Rule Resource','Rule Default');
    SELECT '3. PROPERTIES USED IN RULES SHOULD EXIST IN WOC_PROPERTY_MASTER -- EXP_LHS_VALUE'
         FROM DUAL;
    SELECT
         'RELATION_OWNER,EXP_LHS_OPERAND,RELATION_SIDE,RELATION_ID,EXP_LHS_VALUE,RELATION_TYPE'     
         FROM DUAL;
    SELECT
         b.relation_owner               ||','||
         a.exp_lhs_operand               ||','||
         a.relation_side                    ||','||
         a.relation_id                    ||','||
         a.exp_lhs_value                    ||','||
         b.relation_type
         FROM woc_relation_expression a, woc_relation b
         WHERE a.exp_lhs_value IS NOT NULL
         AND a.exp_lhs_value_type = 'Property'
         AND a.exp_lhs_value NOT IN (SELECT property_name FROM woc_property)
         AND b.product_model_name = 'Graco_Product'
         AND a.relation_id = b.relation_id;
    SELECT '--------------------------------------------------------------------------------'
    from dual;
    spool off
    set head on
    set feedback on

    High level description
    Full documentation
    Note that the UTL_ and DBMS_ packages are all covered in the PL/SQL Packages and Types Reference.
    You may also want to read up on the CREATE DIRECTORY statement, which lets you refer to an actual OS directory (which you create separately) via a database object.

  • How to write ABAP Logic in SAP Query to fetch records from many Tables

    Hi Expert,
    I have one requirement, want to display all BOM (Equipment BOM, Function Location BOM and Meterial BOM) from a particular plant.
    List of tables as below:
    EQST: Equipment to BOM Link
    TPST: Link Between Functional Location and BOM
    MAST: Material to BOM Link
    STPO:BOM item
    Requirement: When user enters Plant then SAP Query should execute and fetch all BOMs (as mentioned above) from STPO Table.
    I have done so far is as follows:
    I create User Group, Infoset and SAP Query.
    While creating INFOSET, i used 4 tables (EQST,TPST,MAST & STPO) and link between then is as follows:
    STPO-STLNR ---> EQST-STLNR : Left Outer Join
    STPO-STLNR ---> TPST-STLNR : Left Outer Join
    STPO-STLNR ---> MAST-STLNR : Left Outer Join
    Now its showing all BOM from all plants though I enter one Plant value.
    Please advise me to write SAP Query and Logic to fetch all BOM from selected Plant Value.
    Thanks,
    Jay.
    Edited by: jaykrishna007 on Jul 29, 2011 11:41 AM

    Hi FCannavo,
    Thanks for your quick reply.
    See, now I changed my Infoset design.
    I added one Plant Table (T001W) and then
    T001W-WERKS--->EQST-WERKS
    T001W-WERKS--->MAST-WERKS
    T001W-WERKS--->TPST-WERKS
    and then
    EQST-STLNR--->STPO-STLNR
    MAST-STLNR--->STPO-STLNR
    TPST-STLNR--->STPO-STLNR
    on selection screen, user will enter Plant Value.
    Now its showing some records, but i dont think so i would be correct output or not, please guide me whether it is correct or not?
    Thanks,
    Jay.

  • How to write a procedure

    hii am new to oracle , can u help me how to write a procedure for the following query
    Transfer Funds between Accounts:
    Table: AccountMaster (AcctNo (primary key), AcctHolderName, currentBal
    Data: 1, 'A', 1000
    2, 'B', 3000
    3, 'C', 4000
    Function: getBalance (AcctNo)
    Stored Proc: tranferFunds (FromAcctNo IN, ToAcctNo IN, Amt IN, result OUT)
    The proc should use the function getBalance (AcctNo) to find out the current balance for account.
    The proc should return a value of 1 if the transfer was successful.
    It should return a value of -1 if the funds are not sufficient in the fromAccount to transfer.
    Thanx ,
    Raj0412

    I would start by asking your teacher to clarify the parts of the assignment that are not clear to you.
    You may also want to read some books.
    http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/toc.htm
    http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/toc.htm

  • How to write a procedure for update the table

    Hi all
    can any body please tell me how to write a procedure to update the table......
    I have a table with about 10,000 records...........Now I have add a new column and I want to add values for that like
    registration Code Creidits
    13213 BBA
    1232 MCS
    I had add the creidit now i want to update the table.........the new value want to get by SQL like
    Creidit = select creidit from othere_table...........
    Hope u can understand my problem
    Thanks in advance
    Regards
    Shayan
    [email protected]

    Please try the following --
    update Program_reg a
    set TotalCreidit = ( select tot_cr <Accroding to your logic>
                                from Program_reg b
                                where a.Registration = b.Registration
                                and    a.Enrollment = b.Enrollment
                                and    a.code = b.code
    where a.Registration in ( select distinct Registration
                                        from Program_reg );
    N.B.: Not Tested....
    Regards.
    Satyaki De.

  • How will write SQL query to fetch data from  each Sub-partition..

    Hi All,
    Anyone does have any idea about How to write SQL query to fetch data from Sub-partition.
    Actually i have one table having composite paritition(Range+list)
    Now if i want to fetch data from main partition(Range) the query will be
    SELECT * FROM emp PARTITION(q1_2005);
    Now i want to fetch data at sub-partition level(List) .But i am not able to get any SQL query for that.
    Pls help me to sort out.
    Thanks in Advance.
    Anwar

    SELECT * FROM emp SUBPARTITION(sp1);

  • How to write a procedure to run the call the custom package from backend

    Hi All
    Oracle 10g
    Oracle Apps R12
    I am working with oracle order management here we have a customize Package called (Pick Release).Due to some problem we have running this concurrent program by manually giving Route_id as parameter. The route_id is taken from the route Table. By using this query
    select distinct route_id from route@DB_LINK_APPS_TO_ROADSHOW
    where trunc(route_date) = trunc (sysdate+2).
    so daily we have nearly 42 routes and we are running this concurrent program manually nearly times.
    so now how to write a procedure for this
    Step 1 Getting the route from route table.( By cursor we can get the route_id Accordingly)
    Step 2 How to trigger the custom package from back end and execute accordingly to that output of the cursor(route_id)
    If the cursor get 40 routes is it then the concurrent program runs 40 times according to that route_id.
    can some could provide the steps to do this
    Thanks & Regards
    Srikkanth.M

    This is about 4 or 5 lines of PL/SQL and the name of the custom package is not provided.
    If you request someone in this forum to do your work for free -because obviously you didn't even try to write it, which must be considered abusing this forum- you must at least provide sufficient info so someone can do it.
    And no, I won't do it for you.
    Sybrand Bakker
    Senior Oracle DBA

  • How to write such procedure?

    I have a DML trigger on a table. whenever there is a change to the table, the old records will be written to another backup table created before. I want to implement this for many tables in the database. Basically, I want a procedure that takes table name as an input and creats a backup table and a trigger for the input table.
    How to write such procedure?
    thanks.

    ...a simple block to get you started...not tested:
    declare
      t varchar2(64) := 'my_table'; --your table name as a parameter
    begin
      execute immediate 'create table '  || t || '_bck as select * from user_tables where 1 = 0';
      -- thinking you'd create the trigger on your base table, not the backup
      execute immediate 'create trigger ' || t || '_dml_trigger before delete or insert or update on ' || t || ' referencing...you get the point
    end;Hope this helps. If you're not the DBA you may want to discuss this train of thought with him/her.
    Cheers.

  • How to do search of business partner data, using a message from external sy

    Hi CRM Gems,
    please send the answer to the following question.
    1.How to do search of business partner data, using a message from external system. What FM’s, BAPI etc that can be used for this functionality?
    your answer will be valuble to me.
    Regards,
    Krishna..

    Hi krishna,
      Look at BAPI   BAPI_BUPA_SEARCH.
    Regards.
    Manuel

  • How can i stop transfer data to Trfc queue from a table datasource.help!!!

    how can i stop transfer data to Trfc queue from a table datasource.
    I create a incorrect view datasource in R3 with wrong join condition,it contain so large data,i want to stop it collect data to sm58.otherwise the system will be ...
    i can't find helpful infrmation in sm50 .
    in sm37 has a canceled job
       Job                              Ln Job CreatedB Status          Start date Start time Duration(sec.) Delay (sec.)
       BIREQU_4EFQCFFUQL5ZOAWYOK2L0YCMF    ALEREMOTE    Canceled        2009-07-10 16:38:59         101,869            0
    plesse help me 。

    Hi,
    You paste the job name in source system in
    Tcode :Sm37
    Job name as :BIREQU_4EFQCFFUQL5ZOAWYOK2L0YCMF
    User:*
    Go to job details and get the PID no ,on which application number it is runnug
    GO to sm51 ,here you will find the application servers,Select the appriate app server go to that PID.
    On left top most you will find option as cancel with out core ..
    OR
    Ask basics team do the same.
    Regards,
    Suman
    Edited by: suman on Jul 13, 2009 12:56 PM

  • How can I get data in flat file from Pool table and cluster table ?

    Hi,
    I am working in one Achiving project. My requirement is to get data into flat file from Cluster table and pool table.
    Is there any tool avilable to download data into flat file from pool table and cluster table ?
    if table name given in the selection screen then data will be downloaded into flat file.
    waiting for quick response.
    Best Regards,
    Bansidhar

    Data cannot be retrived directly form the cluster table
    as the Cluster results are stored in Cluster Key say for example PCLkey
    and form that Key we need to fetch the data
    these clustes are not the part of PNP or PNPCE tables
    for ur info kindly check

  • STO Delivery Date is not copy from Allocation Table Site Date

    Hi,
    I have a problem when Stock Transfer Order created based on the Allocation Table, the delivery date is not copy from Allocation Table. E.g. In Allocation Table delivery date is 26.09.2009, but in STO delivery date is 06.11.2009.
    Check the configuration and also check the stock, there is stock available to be delivered on 26.09.2009.
    Can someone please give me a hint to find out what is missing or wrong, and how to fixed this?
    Greatly appreciate for your suggestion and sharing.
    Kind Regards,
    2tea

    I found the problem finally.

  • Fm or metod that retrieve the lock object name from the table name

    HI ALL,
    there is FM or method that retrieve the lock object name from the table name ?
    Best regards
    Nina

    CALL FUNCTION 'ENQUEUE_REPORT'            
    EXPORTING                                
    gclient                     = sy-mandt   
    gname                       = 'RCTMV'         "Table Name
      GTARG                       = ' '       
      GUNAME                      = SY-UNAME  
    IMPORTING                                 
      number                      =           
      SUBRC                       =           
      TABLES                                  
        enq                         =  lt_seqg3
    EXCEPTIONS                               
       communication_failure       = 1        
       system_failure              = 2        
       OTHERS                      = 3

  • How to write a procedure to load the data into a table using xml file as input to the procedure?

    Hi,
    Iam new to the xml,
    can u please anyone help me how to write procedure to load the data into a table using xml as input parameter to a procedure and xml file is as shown below which is input to me.
    <?xml version="1.0"?>
    <DiseaseCodes>
    <Entity><dcode>0</dcode><ddesc>(I87)Other disorders of veins - postphlebitic syndrome</ddesc><claimid>34543></claimid><reauthflag>0</reauthflag></Entity>
    <Entity><dcode>0</dcode><ddesc>(J04)Acute laryngitis and tracheitis</ddesc><claimid>34543></claimid><reauthflag>0</reauthflag></Entity>
    <Entity><dcode>0</dcode><ddesc>(J17*)Pneumonia in other diseases - whooping cough</ddesc><claimid>34543></claimid><reauthflag>0</reauthflag></Entity>
    </DiseaseCodes>.
    Regards,
    vikram.

    here is the your XML parse in 11g :
    select *
      from xmltable('//Entity' passing xmltype
    '<?xml version="1.0"?>
    <DiseaseCodes>
    <Entity><dcode>0</dcode><ddesc>(I87)Other disorders of veins - postphlebitic syndrome</ddesc><claimid>34543></claimid><reauthflag>0</reauthflag></Entity>
    <Entity><dcode>0</dcode><ddesc>(J04)Acute laryngitis and tracheitis</ddesc><claimid>34543></claimid><reauthflag>0</reauthflag></Entity>
    <Entity><dcode>0</dcode><ddesc>(J17*)Pneumonia in other diseases - whooping cough</ddesc><claimid>34543></claimid><reauthflag>0</reauthflag></Entity>
    </DiseaseCodes>
    ') columns
      "dcode" varchar2(4000) path '/Entity/dcode',
      "ddesc" varchar2(4000) path '/Entity/ddesc',
      "reauthflag" varchar2(4000) path '/Entity/reauthflag'
    dcode                                                                            ddesc                                                                            reauthflag
    0                                                                                (I87)Other disorders of veins - postphlebitic syndrome                           0
    0                                                                                (J04)Acute laryngitis and tracheitis                                             0
    0                                                                                (J17*)Pneumonia in other diseases - whooping cough                               0
    SQL>
    Using this parser you can create procedure as
    SQL> create or replace procedure myXMLParse(x clob) as
      2  begin
      3    insert into MyXmlTable
      4      select *
      5        from xmltable('//Entity' passing xmltype(x) columns "dcode"
      6                      varchar2(4000) path '/Entity/dcode',
      7                      "ddesc" varchar2(4000) path '/Entity/ddesc',
      8                      "reauthflag" varchar2(4000) path '/Entity/reauthflag');
      9    commit;
    10  end;
    11 
    12  /
    Procedure created
    SQL>
    SQL>
    SQL> exec myXMLParse('<?xml version="1.0"?><DiseaseCodes><Entity><dcode>0</dcode><ddesc>(I87)Other disorders of veins - postphlebitic syndrome</ddesc><claimid>34543></claimid><reauthflag>0</reauthflag></Entity><Entity><dcode>0</dcode><ddesc>(J04)Acute laryngitis and tracheitis</ddesc><claimid>34543></claimid><reauthflag>0</reauthflag></Entity><Entity><dcode>0</dcode><ddesc>(J17*)Pneumonia in other diseases - whooping cough</ddesc><claimid>34543></claimid><reauthflag>0</reauthflag></Entity></DiseaseCodes>');
    PL/SQL procedure successfully completed
    SQL> select * from MYXMLTABLE;
    dcode                                                                            ddesc                                                                            reauthflag
    0                                                                                (I87)Other disorders of veins - postphlebitic syndrome                           0
    0                                                                                (J04)Acute laryngitis and tracheitis                                             0
    0                                                                                (J17*)Pneumonia in other diseases - whooping cough                               0
    SQL>
    SQL>
    Ramin Hashimzade

  • How to write a procedure using collections

    how can we define collections inside procedure and use it
    i am getting an error executing this proc
    create or replace procedure p_collections
    is
    type calendar is varray(366) of  date;
    calendar c1;
    begin
    for i in 1 .. 100
    loop
    select sysdate bulk collect into c1 from dual;
    end loop;
    DBMS_OUTPUT.PUT_LINE(c1);
    end;Edited by: Rahul_India on Sep 12, 2012 2:54 PM
    Edited by: Rahul_India on Sep 12, 2012 3:07 PM

    That's because you only have one value in the array.
    Here is sample code that you can test in the SCOTT schema.
    set serveroutput on;
    declare
      cursor my_cur is
      select empno from emp;
      type my_type is table of emp.ename%type;
      type my_type2 is table of emp.empno%type;
      dizi my_type;
      dizi2 my_type2;
      query VARCHAR2(100);
    begin
      open my_cur;
      fetch my_cur bulk collect into dizi2;
      close my_cur;
      for i in dizi2.first..dizi2.last
      loop
        dbms_output.put_line(dizi2(i));
      end loop;
    end;
    /Or another sample using a LIMIT clause
    The FETCH does a BULK COLLECT of all data into 'v'. It will either get all the data or none if there isn't any.
    The LOOP construct would be used when you have a LIMIT clause so that Oracle would 'loop' back to
    get the next set of records. Run this example in the SCOTT schema and you will see how the LIMIT clause works.
    I have 14 records in my EMP table.
    DECLARE
      CURSOR c1 IS (SELECT * FROM emp);
      TYPE typ_tbl IS TABLE OF c1%rowtype;
      v typ_tbl;
    BEGIN
      OPEN c1;
      LOOP                                                 --Loop added
        FETCH c1 BULK COLLECT INTO v LIMIT 3; -- process 3 records at a time
            -- process the first 3 max records
           DBMS_OUTPUT.PUT_LINE('Processing ' || v.COUNT || ' records.');
            FOR i IN v.first..v.last LOOP
                DBMS_OUTPUT.PUT_LINE(v(i).empno);
            END LOOP; 
        EXIT WHEN c1%NOTFOUND;
      END LOOP;
      DBMS_OUTPUT.PUT_LINE('All done');
    END;In the FOR loop you would do any processing of the nested table you want to do
    and could use a FORALL to do an INSERT into another table.

Maybe you are looking for

  • Iphone Cannot connect to itunes. Ox E8000003

    i have tried to restore the phone and that didnt help

  • Expdp logfile needs to be sent

    Hi, I'm using oracle 11g with Aix box, i have a script for data export with help of datapump, now i want to send the mail with attached the export process log file to multiple list of mails, can we use mailx option in aix box , if yes , is there pre

  • Building a 240gb IPOD classic 6th generation???

    I have been doing a lot of research and I haven't found an exact answer to my question. Right now I have a 6th generation 80GB ipod classic. I have run out of storage and I really need 240GB. I bought a rebuilt 240GB 7th generation Ipod from ebay a f

  • Invalid relational operator

    Hi, if I : create table t (a number, b number, c number); and then run the following query: delete from t where a='1' and (b, c) in ( select b, c from t where a='1' group by b, c having count(*) > 1); -- nothing to see here I get the following error:

  • Is there any corporate database available for Multisim12?

    I'm trying Multisim12. Master database has a lot of components but I wonder there many simple and common ICs are missing while I have noticed that many of these components are readily available in Proteus etc.  I'm especially talking about CMOS 4000