Insert into cursor one at a time

Hello,
Is it possible to insert one value per cycle execution on a cursor? For example:
c_anuncios cursor_anuncios;
c_result my_result_cursor;
BEGIN
     LOOP
          EXIT WHEN(c_anunciantes%NOTFOUND);
--get one comparison value
          FETCH c_anunciantes INTO idAnunciante;          
          SELECT * FROM anuncio a
          --INTO where? how do I record this single value on c_result
          WHERE a.anunciante=id_anunciante;
     END LOOP;
RETURN c_result;
There's no way (that I can think of) that I can do "OPEN c_result FOR SELECT"... because I always need to do as many queries as I have elements on the "c_anunciantes" cursor, correct?
Thanks in advance! :)

If I understand correctly, you want to gather 5 id numbers in a cursor and then open a cursor using each of those 5 keys and then have access to all of the rows returned by the 5 cursors in the same structure.
Will this version of your query compile?
OPEN c_anuncios FOR
SELECT *
FROM anuncio a3
WHERE anunciante IN (SELECT a1.id
FROM anunciante a1, anuncio a2
WHERE a2.anunciante = a1.id
AND a2.palavra_chave = 3
AND rownum < 6
HAVING COUNT(a1.id) > 0
ORDER BY COUNT(a1.id) DESC, SUM(a2.preco) DESC, a1.id ASC
GROUP BY a1.id)
ORDER BY a3.preco DESC, a3.num_cliques DESC, a3.id ASC;
Perhaps the following example would satisfy your requirement. It is certainly not strictly set based but bulk binding will reduce the number of context switches required to run the PL/SQL.
DECLARE
-- this procedure will loop through a set of keys to open a set of cursors
-- and store all rows from those cursors in a collection
-- the final set of records can be referenced individually by subscript 1..n
TYPE five_row_typ IS VARRAY(5) OF anunciante.id%TYPE;
five_rows five_row_typ; -- to store the 5 keys to intermediate datasets
TYPE anuncio_tbl_typ IS TABLE OF anuncio%ROWTYPE;
anuncio_tbl anuncio_tbl_typ;
-- to store the intermediate result set for each of the 5 rows
total_anuncio_tbl := anuncio_tbl_typ(); -- initialize an empty collection
--to hold result sets from each of the 5 queries
CURSOR anunciante_cur(p_chave anunciante.id%TYPE, p_rows NUMBER) IS
SELECT a1.id
FROM anunciante a1, anuncio a2
WHERE a2.anunciante = a1.id
AND a2.palavra_chave = p_chave
AND rownum < p_rows + 1
GROUP BY a1.id
HAVING COUNT(a1.id) > 0
ORDER BY COUNT(a1.id) DESC, SUM(a2.preco) DESC, a1.id ASC;
CURSOR anuncio_cur(p_id anuncio.anunciante%TYPE) IS
SELECT *
FROM anuncio a3
WHERE anunciante = p_id
ORDER BY a3.preco DESC, a3.num_cliques DESC, a3.id ASC;
k NUMBER := 0;
BEGIN
OPEN anunciante_cur(3, 5);
FETCH anunciante_cur BULK COLLECT
INTO five_rows; -- this will get all keys for cursors that follow
CLOSE anunciante_cur;
IF five_rows.EXISTS(1)
THEN
FOR i IN five_rows.FIRST .. five_rows.LAST
LOOP
OPEN anuncio_cur(five_rows(i));-- cursor will be opened p_rows times
LOOP
FETCH anuncio_cur BULK COLLECT
INTO anuncio_tbl;-- this will get all rows from a single cursor in one pass
-- each of the 5 intemediate result sets will pass through this collection
IF anuncio_tbl.EXISTS(1)
THEN
FOR j IN anuncio_tbl.FIRST .. anuncio_tbl.LAST
LOOP
k := k + 1;
total_anuncio_tbl.EXTEND;
total_anuncio_tbl(k) := anuncio_tbl(i);
-- and each element (row) of each of the 5 result sets will end here
-- whether there is one or many rows in each set
END LOOP;
END IF;
EXIT WHEN anuncio_cur%NOTFOUND OR anuncio_cur%NOTFOUND IS NULL;
END LOOP;
CLOSE anuncio_cur;
END LOOP;
END IF;
END;
Regards,
Peter

Similar Messages

  • How do I insert textarea values one at a time into database?

    I have a a simple form:
    Select List - populated by a recordset that gets a list of technicians.   In this format:   Label - >  Tech name   Value - > Tech ID
    Textarea - To paste zip codes into that the tech services.    In this format:   12345,12346,12347,etc..
    When I want to submit the form, I want it to take all of those zip codes and insert them into the database as a single record each with the tech's id from the select list. 
    The code I have is thus:
    $zipcodes = explode(",", $_POST['textarea']);
    $countZips = (count($zipcodes));
    if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
    foreach($zipcodes as $key=>$value)
    while ($countZips >= 1) {
    $editFormAction = $_SERVER['PHP_SELF'];
    if (isset($_SERVER['QUERY_STRING'])) {
      $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
      $insertSQL = sprintf("INSERT INTO zip_zip (zip_code, tech_id) VALUES (%s, %s)",
                           GetSQLValueString($value, "int"),
                           GetSQLValueString($_POST['select'], "int"));
      mysql_select_db($database_localhost, $localhost);
      $Result1 = mysql_query($insertSQL, $localhost) or die(mysql_error());
              $countZips--;
    //Done value exists
    //Now moving to next page when done
              $insertGoTo = "index.php";
      if (isset($_SERVER['QUERY_STRING'])) {
        $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
        $insertGoTo .= $_SERVER['QUERY_STRING'];
      header(sprintf("Location: %s", $insertGoTo));
    //END
    The issue is - let's say I paste 105 zip codes into the text area.   It will insert the FIRST zip code 105 times into the database instead of inserting the 105 zip codes individually.
    Any idea what I'm doing wrong here?
    Thanks!

    Ok, so all of that mysql stuff just needs to be ran once until the connection is closed.  I didn't know that.  That probably makes it run better too.
    Ok, so here is what that code looks like now.  There are a few additions because it turns out I also have to check to make sure the zip code is in a state that the tech is licensed in.  : (  I have a question about how to do that because it is different.  Do I need to post a new question or is better to ask here since my stuff is usually in left field?
    Any way here is my code now.  I think it is much better, right?
    //Start
    //This is my recordset to get the last tech added
    mysql_select_db($database_localhost, $localhost);
    $query_getTechs = "SELECT * FROM zip_tech ORDER BY tech_id DESC";
    $getTechs = mysql_query($query_getTechs, $localhost) or die(mysql_error());
    $row_getTechs = mysql_fetch_assoc($getTechs);
    $totalRows_getTechs = mysql_num_rows($getTechs);
    //This is where I'm getting all zip codes that are serviceable by stupid regulations
    mysql_select_db($database_localhost, $localhost);
    $query_Recordset1 = "SELECT zip_code, state_prefix FROM zip_code";
    $Recordset1 = mysql_query($query_Recordset1, $localhost) or die(mysql_error());
    $row_Recordset1 = mysql_fetch_assoc($Recordset1);
    $totalRows_Recordset1 = mysql_num_rows($Recordset1);
    //ARRAYS
    $results = array();
    $states = array();
    do {
      $results[] = $row_Recordset1['zip_code'];
      $states[] = $row_Recordset1['state_prefix'];
    } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1));
    //Check if form is filled out
    if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
    //If so, explode textarea values into an array or something
    $zipcodes = explode(",", $_POST['textarea']);
    //MySQL Stuff
    mysql_select_db($database_localhost, $localhost);
    $editFormAction = $_SERVER['PHP_SELF'];
    if (isset($_SERVER['QUERY_STRING'])) {
    $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
    //my loop to go through each zip code one by one
    foreach($zipcodes as $value)
    //Let's see if the value from the textarea is in our $results array from above
    if (in_array($value, $results)){
    //If it is in the array - then insert it into the database with the tech id
      $insertSQL = sprintf("INSERT INTO zip_zip (zip_code, tech_id) VALUES (%s, %s)",
                           GetSQLValueString($value, "int"),
                           GetSQLValueString($_POST['tech_id'], "int"));
      $Result1 = mysql_query($insertSQL, $localhost) or die(mysql_error());
    //Done value exists
    //Now moving to next page when done
              $insertGoTo = "index.php";
      if (isset($_SERVER['QUERY_STRING'])) {
        $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
        $insertGoTo .= $_SERVER['QUERY_STRING'];
      header(sprintf("Location: %s", $insertGoTo));
    //END
    Message was edited by: Drymetal

  • Sql Script containing INSERT INTO TABLE_NAME taking very long time

    Version:11g
    I have a .sql file which contains insert statements for the table ZIP_CODES like.
    INSERT INTO ZIP_CODES (ZIP_CODE, CITY, PROV, COUNTRY_CODE, LONGITUDE, LATITUDE)
    VALUES (..........);This sql file contains above 800,000 INSERT statements like these! Execution of this file takes around 20 minutes.
    Our client insists that they need a script to create this table and not a dump file (export dump of just this table)
    Is there any way i could speed up these INSERTs in this script. I have added a commit half way through this file because i was worried about UNDO tablespace.
    This table (ZIP_CODES) is not dependant on any other table (no FKs, no FK references,..).
    Edited by: Steve_74 on 03-Sep-2009 05:53

    One possible option is to use External Tables
    1. Create a CSV file with the values to be stored in the table.
    2. Create an directory object (The location where the CSV file will be stored)
    3. Create an External Table pointing to the CSV file
    4. Just do a INSERT INTO ZIP_CODES SELECT * FROM <external table> (may be try to use a APPEND hint)
    5. Drop the Directory object and External Table.

  • HOW TO EXECUTE TWO "INSERT INTO" IN ONE SQL QUERY?????

    i have try the following:
    INSERT INTO tab VALUES('a','b');
    INSERT INTO tab VALUES('c','d');
    and
    INSERT INTO tab VALUES('a','b');
    INSERT INTO tab VALUES('c','d');
    but does not work in ORACLE 10G XE
    please help!!

    It is working fine in Oracle 10g.
    SQL> desc emp_t;
    Name                                      Null?    Type
    EMPNO                                              NUMBER(4)
    ENAME                                              VARCHAR2(10)
    JOB                                                VARCHAR2(9)And the script is --
    insert into emp_t values(7799,'Ani','CLERK');
    insert into emp_t values(2233,'Rupak','SW');  --File Name is a_a.sql
    commit;And, now from command prompt --
    SQL> set serveroutput on
    SQL>
    SQL>
    SQL> set lin 1000
    SQL>
    SQL> select * from emp_t;
         EMPNO ENAME      JOB
          7777 Avik       CLERK
          6666 prithwi    CLERK
          7639 Roni       CLERK
          7499 ALLEN      SALESMAN
          7521 WARD       SALESMAN
          7566 JONES      MANAGER
          7654 MARTIN     SALESMAN
          7698 BLAKE      MANAGER
          7782 CLARK      MANAGER
          7788 SCOTT      ANALYST
          7839 KING       PRESIDENT
         EMPNO ENAME      JOB
          7844 TURNER     SALESMAN
          7876 ADAMS      CLERK
          7900 BARRY      CLERK
          7902 FORD       ANALYST
          7934 MILLER     CLERK
          5639 Atul       CLERK
    17 rows selected.
    SQL> @C:\Personal\RND\Oracle\Misc\a_a.sql;
    1 row created.
    1 row created.
    Commit complete.
    SQL>
    SQL>
    SQL> select * from emp_t;
         EMPNO ENAME      JOB
          7799 Ani        CLERK
          2233 Rupak      SW
          7777 Avik       CLERK
          6666 prithwi    CLERK
          7639 Roni       CLERK
          7499 ALLEN      SALESMAN
          7521 WARD       SALESMAN
          7566 JONES      MANAGER
          7654 MARTIN     SALESMAN
         EMPNO ENAME      JOB
          7698 BLAKE      MANAGER
          7782 CLARK      MANAGER
          7788 SCOTT      ANALYST
          7839 KING       PRESIDENT
          7844 TURNER     SALESMAN
          7876 ADAMS      CLERK
          7900 BARRY      CLERK
          7902 FORD       ANALYST
          7934 MILLER     CLERK
          5639 Atul       CLERK
    19 rows selected.Regards.
    Satyaki De.

  • Emails from Inbox moving into Outbox one at a time, can't stop them!!!

    This behavior just started - I'm using Mail 3.6 (936) and OSX 10.5.8. My Outbox contantly has one email in it, and the email is always an old one taken from my Inbox... an email TO me, and not one I am trying to send. If I delete the email from the Outbox, then click out of/back into the Outbox, another single email from my Inbox will have taken its place. Starting Mail with these emails in the Outbox results in an SMTP error because the mail is not 'sendable'... every time, since I am unable to completely clean out the Outbox.
    I've tried re-starting, rebuilding all mailboxes, etc... with no success. What happened here?

    Quit Mail, and in the Finder open Home/Library/Mail/Mailboxes and locate the Outbox.mbox folder. Delete this folder and relaunch Mail. When you next compose and send a message Mail will create a new Outbox.mbox.
    See if this behavior is corrected?
    Ernie

  • How can i insert more than one record a time in a JSP page?

    Hi experts,
    I'm working with JDeveloper version 3.2 application server 9i.
    I want to insert more than 1 record using a jsp page and then perform a commit at the end.
    do you can help me with this problem/challenge?
    Thank you,
    Regards,
    Mario

    statement.executeBatch() maybe?

  • Create Trigger to insert records from one table to another

    I created the below trigger to move data from one table to another after records have been inserted from another table to that table. What I need done is that each time records have been inserted into TEST_TBL, one of these actions codes should be implimented: U-update, N-insert, D-delete and inserted into TEST_TBL1. But each time I run the script, I get bunch of errors. Please see the script below: - Your help will be appreciated.
    create or replace
    trigger POWER_tr
    after update or insert or delete ON test_tbl
    for each row
    begin
    if updating then
    insert into test_tbl1
    (idx, mke, ctl, ori, nam, sex, rac, pob, dob, hgt, action_code, date_added
    VALUES
    (idx, mke, ctl, ori, nam, sex, rac, pob, dob, hgt, 'U', sysdate);
    ELSif INSERTING then
    insert insert into test_tbl1
    (idx, mke, ctl, ori, nam, sex, rac, pob, dob, hgt, action_code, date_added
    VALUES
    (idx, mke, ctl, ori, nam, sex, rac, pob, dob, hgt, 'N', sysdate);
    ELSIF deleting then
    insert into test_tbl1
    (idx, mke, ctl, ori, nam, sex, rac, pob, dob, hgt, action_code, date_added
    VALUES
    (idx, mke, ctl, ori, nam, sex, rac, pob, dob, hgt, 'D', sysdate);
    END IF;
    END POWER_tr;
    Thank you,
    Albert Zaza
    Edited by: azaza on Mar 1, 2009 4:14 PM

    Hello
    At the end of trigger show errors / and post what errors are you getting exactly?
    Here is a simple example for your reference, this will save old values in history table; you can replace it with new values if that's what do you want.
    CREATE OR REPLACE TRIGGER TRG_DU
       AFTER DELETE OR UPDATE
       ON EMPLOYEE    REFERENCING NEW AS New OLD AS Old
       FOR EACH ROW
    DECLARE
    BEGIN
       IF UPDATING
       THEN
          INSERT INTO employee_hist
            VALUES   ('UPDATE',
                      :OLD.empid,
                      :OLD.name,
                      :OLD.deptid);
       ELSIF DELETING
       THEN
          INSERT INTO employee_hist
            VALUES   ('UPDATE',
                      :OLD.empid,
                      :OLD.name,
                      :OLD.deptid);
       END IF;
    EXCEPTION
       WHEN OTHERS
       THEN
          -- Consider logging the error and then re-raise
          RAISE;
    END TRG_DU;
    /Regards
    Edited by: OrionNet on Mar 1, 2009 7:27 PM

  • I can only delete photos one at a time.  Why?

    Why can't I delete multiple photos after they've been moved to trash?  I can't empty the trash.  If I put them into trash one at a time and empty it one at a time, it works. 
    There must be an easy trick to deleting lots of photos, all at once.
    Help, anyone?

    What version of iPhoto? Assuming 09 or later:
    Option 1
    Back Up and try rebuild the library: hold down the command and option (or alt) keys while launching iPhoto. Use the resulting dialogue to rebuild. Choose to Rebuild iPhoto Library Database from automatic backup.
    If that fails:
    Option 2
    Download iPhoto Library Manager and use its rebuild function. This will create a new library based on data in the albumdata.xml file. Not everything will be brought over - no slideshows, books or calendars, for instance - but it should get all your albums and keywords back.
    Because this process creates an entirely new library and leaves your old one untouched, it is non-destructive, and if you're not happy with the results you can simply return to your old one. .
    Regards
    TD

  • How to insert into more than one table at a time also..

    hi,
    i am a newbee.
    how to insert into more than one table at a time
    also
    how to get a autoincremented value of an id say transactionid for a particular accountid.
    pls assume table as
    transactionid accountid
    101 50
    102 30
    103 50
    104 35
    i want 102 for accountid 30 and 103 for accountid 50.
    thank u

    @blushadow,
    You can only insert into one table at a time. Take a look here :
    Re: insert into 2 tables
    @Raja,
    I want how to extract the last incremented value not to insert.Also, I don't understand your thread title... which was "how to insert into more than one table at a time also.. "
    Insert, extract... ? Can you clarify your job ?
    Nicolas.

  • "Insert into Multitrack" keeps inserting on new track instead of one I've selected

    Hello, Everyone!
    I've just installed Audition 3.0 (upgraded from 1.5) on Windows Vista. Looks great, but when selecting a section of audio from the edit window for "Insert into Multitrack," it keeps putting the clip/selection on the next unused track instead of the track I've selected, despite what I do. Its all from one audio file and the clips are short, so it doesn't appear to be a time issue or difference in file type. I'm assuming its something simple relating to the mulittrack/edit window set-up I'm missing that I haven't seen yet.
    Any Ideas?
    Here are some pics below ...
    Track is selected and marker line (or whatever its called) is at appropriate point, just like in Audition 1.5 (note highlighted track) ...
    Then selection/clip is higlighted in Edit Window, then "Insert" is selected, ...
    But puts clip here anyway (note highlighted clip) ...
    So that's what's going on ... any suggestions?
    Thanx!
    ---Ron

    Not that I'm aware of, but I'll check it out. The problem is, it shouldn't be doing that at all, even if it is overlapping ... every single solitary audio editing software I've ever used (Saw, CakeWalk, ProTools, Audition 1.5, etc.,) puts the clip where ever the cursor is, so I have to believe its something I'm missing ... some box I need to uncheck somewhere or something.
    ---R

  • How to insert into two differents tables at the same time

    Hi
    I'm newer using JDev, (version 3.1.1.2 cause the OAS seems to support just the JSP 1.0)
    and I want to insert into two differents tables at the same time using one view.
    How can I do that ?
    TIA
    Edgar

    Oracle 8i supports 'INSTEAD OF' triggers on object views so you could use a process similar to the following:
    1. Create an object view that joins your two tables. 'CREATE OR REPLACE VIEW test AS SELECT d.deptno, d.deptname, e.empname FROM DEPT d, EMP E'.
    2. Create an INSTEAD OF trigger on the view.
    3. Put code in the trigger that looks at the :NEW values being processed and determines which columns should be used to INSERT or UPDATE for each table. Crude pseudo-code might be:
    IF :NEW.deptno NOT IN (SELECT deptno FROM DEPT) THEN
    INSERT INTO dept VALUES(:NEW.deptno, :NEW.deptname);
    INSERT INTO emp VALUES (:NEW.deptno, :NEW.empname);
    ELSE
    IF :NEW.deptname IS NOT NULL THEN
    UPDATE dept SET deptname = :NEW.deptname
    WHERE deptno = :NEW.deptno;
    END IF;
    IF :NEW.empname IS NOT NULL THEN
    UPDATE emp SET empname = :NEW.empname
    WHERE deptno = :NEW.deptno;
    Try something along those lines.
    null

  • How to read LONG RAW data from one  table and insert into another table

    Hello EVERYBODY
    I have a table called sound with the following attributes. in the music attribute i have stored some messages in the different language like hindi, english etc. i want to concatinate all hindi messages and store in the another table with only one attribute of type LONG RAW.and this attribute is attached with the sound item.
    when i click the play button of sound item the all the messages recorded in hindi will play one by one automatically. for that i'm doing the following.
    i have written the following when button pressed trigger which will concatinate all the messages of any selected language from the sound table, and store in another table called temp.
    and then sound will be played from the temp table.
    declare
         tmp sound.music%type;
         temp1 sound.music%type;
         item_id ITEM;
    cursor c1
    is select music
    from sound
    where lang=:LIST10;
    begin
         open c1;
         loop
              fetch c1 into tmp; //THIS LINE GENERATES THE ERROR
              temp1:=temp1||tmp;
              exit when c1%notfound;
         end loop;
    CLOSE C1;
    insert into temp values(temp1);
    item_id:=Find_Item('Music');
    go_item('music');
    play_sound(item_id);
    end;
    but when i'm clicking the button it generates the following error.
    WHEN-BUTTON-PRESSED TRIGGER RAISED UNHANDLED EXCEPTION ORA-06502.
    ORA-06502: PL/SQL: numeric or value error
    SQL> desc sound;
    Name Null? Type
    SL_NO NUMBER(2)
    MUSIC LONG RAW
    LANG CHAR(10)
    IF MY PROCESS TO SOLVE THE ABOVE PROBLEM IS OK THEN PLESE TELL ME THE SOLUTION FOR THE ERROR. OTHER WISE PLEASE SUGGEST ME,IF ANY OTHER WAY IS THERE TO SOLVE THE ABOVE PROBLEM.
    THANKS IN ADVANCE.
    D. Prasad

    You can achieve this in many different ways, one is
    1. Create another VO based on the EO which is based on the dest table.
    2. At save, copy the contents of the source VO into the dest VO (see copy routine in dev guide).
    3. commiting the transaction will push the data into the dest table on which the dest VO is based.
    I understand that if we attach VO object instance to region/page, we only can pull and put data in to only one table.
    if by table you mean a DB table, then no, you can have a VO based on multiple EOs which will do DMLs accordingly.Thanks
    Tapash

  • Need to insert rows into 100 tables at a time

    hi there,
    below is our script for creation of 100 tables...
    we need a plsql script, to insert rows into 100 tables at a single time...
    please help us...vey urgent...
    DECLARE
    counter NUMBER;
    sql_string VARCHAR2(2000);
    BEGIN FOR counter IN 1..100 LOOP sql_string := 'CREATE TABLE emp_table'||counter||'
    (id integer primary key, col_a VARCHAR2(42),col_b date,col_c number,col_d varchar2(20),col_e varchar2(20),
    col_f varchar2(20),col_g varchar2(20),col_h date,col_i varchar2(20),col_j varchar2(20),col_k date)';
    EXECUTE IMMEDIATE sql_string;
    END LOOP;
    END;
    /

    hi,
    below is our procedure and the error we are getting...
    Name Null? Type
    ID VARCHAR2(10)
    COL_A VARCHAR2(10)
    COL_B VARCHAR2(10)
    COL_C VARCHAR2(10)
    COL_D VARCHAR2(10)
    COL_E VARCHAR2(10)
    COL_F VARCHAR2(10)
    COL_G VARCHAR2(10)
    COL_H VARCHAR2(10)
    COL_J DATE
    DECLARE
    counter NUMBER;
    sql_string VARCHAR2(4000);
    BEGIN FOR counter IN 1..100 LOOP sql_string := 'CREATE TABLE emp_a'||counter||'
    (id varchar2(10), col_a varchar2(10), col_b varchar2(10), col_c varchar2(10), col_d varchar2(10), col_e varchar2(10),
    col_f varchar2(10), col_g varchar2(10), col_h varchar2(10), col_j date)';
    EXECUTE IMMEDIATE sql_string;
    END LOOP;
    END;
    DECLARE
    counter NUMBER;
    sql_string VARCHAR2 (2000);
    BEGIN
    FOR OuterCounter IN 1 .. 100 LOOP --- table prefix in which it is to be inserted
    FOR InnerCounter IN 1 .. 100 LOOP --- records to be inserted
    sql_string := 'INSERT INTO emp_a' || Outercounter || ' (id, col_a, col_b, col_c, col_d, col_e, col_f, col_g, col_h, col_j)
    VALUES ('
    || InnerCounter || ', to_char( ''col_a''' || innercounter || '),'
    || InnerCounter || ', to_char( ''col_d''' || innercounter || '),'
    || ', to_char( ''col_e''' || innercounter || '),'
    || ', to_char( ''col_f''' || innercounter || '),'
    || ', to_char( ''col_g''' || innercounter || '),'
    || ', to_char( ''col_h''' || innercounter || '),'
    || ', to_char( ''col_j''' || innercounter || '), SYSDATE)';
    EXECUTE IMMEDIATE sql_string;
    END LOOP;
    END LOOP;
    END;
    DECLARE
    ERROR at line 1:
    ORA-00907: missing right parenthesis
    ORA-06512: at line 17
    please check the procedure and write the correct one...

  • Stored procedure to insert into multiple tables in sql server 2012, using id col from one table to insert into the other 2

    Hi all,
    Apologies if any of the following sounds at all silly but I am fairly new to this so here goes...
    I have 3 tables that require data insertion at the same time. The first table is the customers table, I then want to take the automatically generated custid from that table and inser it into 2 other tables along with some other data
    Here's what I have so far which does not work:
    CREATE PROCEDURE CustomerDetails.bnc_insNewRegistration @CustId int,
    @CompanyName varchar(100),
    @FirstName varchar(50),
    @LastName varchar(50),
    @Email nvarchar(254),
    @HouseStreet varchar(100),
    @Town smallint,
    @County tinyint,
    @Postcode char(8),
    @Password nvarchar(20)
    AS
    BEGIN
    begin tran
    insert into CustomerDetails.Customers
    (CompanyName, FirstName, LastName, EmailAddress)
    Values (@CompanyName, @FirstName, @LastName, @Email)
    set @CustId = (select CustId from inserted)
    insert into CustomerDetails.Address
    (CustomerId, HouseNoAndStreet, Town, County, PostCode)
    values (@CustId, @HouseStreet, @Town, @County, @Postcode)
    insert into CustomerDetails.MembershipDetails
    (CustomerId, UserName, Password)
    values (@CustId, @Email, @Password)
    commit tran
    END
    GO
    If anyone could help with this I would very much appreciate it as I am currently building an online store, if there's no registration there's no customers.
    So to whom ever is able to help, I thank you whole heartedly :)

    I hope by now it is apparent that statements like "doesn't work" are not particularly helpful. The prior posts have already identified your first problem.  But there are others.  First, you have declared @CustID as an argument for your
    procedure - but it is obvious that you do not expect a useful value to be supplied when the procedure is executed.  Perhaps it should be declared as an output argument so that the caller of the procedure can know the PK value of the newly inserted customer
    - otherwise, replace it with a local variable since it serves no purpose as an input argument.
    Next, you are storing email twice.  Duplication of data contradicts relational theory and will only cause future problems. 
    Next, I get the sense that your "customer" can be a person or a company.  You may find that using the same table for both is not the best approach.  I hope you have constraints to prevent a company from having a first and last name (and
    vice versa).
    Next, your error checking is inadequate.  We can only hope that you have the appropriate constraints to prevent duplicates.  You should expect failures to occur, from basic data errors (duplicates, null values, inconsistent values) to system issues
    (out of space).  I'll leave you with Erland's discussion for more detail:
    erland - error handling.
    Lastly, you should reconsider the datatypes you are using for the various bits of information.  Presumably town and county are foreign keys to related tables, which is why they are numeric.  Be careful you don't paint yourself into a corner with
    such small datatypes.  One can also debate the wisdom of using a separate tables for Town and County (and perhaps the decision to limit yourself to a particular geographic area with a particular civic hierarchy). Password seems a little short to me. 
    And if you are going to use nvarchar for some strings, you might as well use it for everything - especially names.  Also, everyone should be security conscious by now - passwords should be encrypted at the very least.
    And one last comment - you really should allow 2 address lines. Yes, two separate ones and not just one much larger one.

  • Require sum value of one table to be inserted into another table column

    Hi
    I have a table which contains a list of parts and their prices required for an assembly.
    I am trying to calculate the total from this part lists and put into the total price column for the assembly (another table column).
    My method was to calculate the total in a page process ( eg, once all parts in the assembly have been entered the page process calculates the total price (the sum of the part prices at that time) and puts the result (total) in the assembly total column)
    In the process I capture the total using either
    SELECT SUM(TOTAL_COST) Total INTO B from CC_REQ_BOM WHERE RID = :P5_RID;
    or
    SELECT SUM(TOTAL_COST) INTO B from CC_REQ_BOM WHERE RID = :P5_RID;
    Both the above sql statements are allowed ( one with alias and one without alais) by the page process but they dont seem to be working as no total is returned to the table when the page process is run.
    to insert the calculation(variable B) into the required table I have used
    INSERT INTO CC_REQ(TOTAL_COST)
    VALUES(B);
    I have used this method a few times with no problems for standard sql statements but this is the first time I have used it with the sum SQL function. For some reason it doesn't seem to like the SUM function even though the code below works in SQL Command window.
    SELECT SUM(TOTAL_COST) from CC_REQ_BOM WHERE RID = :P5_RID;
    Any help welcome.
    PGJ

    Hi
    In that case, I would do something like this then...
    CREATE TABLE crt_crates
    (ccr_id   INTEGER        CONSTRAINT ccr_pk PRIMARY KEY,
    ccr_name VARCHAR2(4000) CONSTRAINT ccr_nam_nn NOT NULL);
    CREATE TABLE crt_requests
    (cre_id        INTEGER        CONSTRAINT cre_pk PRIMARY KEY,
    cre_reference VARCHAR2(4000) CONSTRAINT cre_ref_nn NOT NULL,
    --I've skipped the requester as this would probably refernce a different table
    --I've skipped request details as it's not necessary for this example
    cre_ccr_id    INTEGER        CONSTRAINT cre_ccr_fk REFERENCES crt_crates);
    CREATE TABLE crt_materials
    (cma_id   INTEGER        CONSTRAINT cma_pk PRIMARY KEY,
    cma_name VARCHAR2(4000) CONSTRAINT cma_nam_nn NOT NULL,
    cma_cost NUMBER(12,2)   CONSTRAINT cma_cos_nn NOT NULL);
    CREATE TABLE crt_crate_bom
    (ccb_id       INTEGER CONSTRAINT ccb_pk PRIMARY KEY,
    ccb_ccr_id   INTEGER CONSTRAINT ccb_ccr_fk REFERENCES crt_crates,
    ccb_cma_id   INTEGER CONSTRAINT ccb_cma_fk REFERENCES crt_materials,
    ccb_quantity INTEGER DEFAULT 1 CONSTRAINT ccb_qua_nn NOT NULL);
    INSERT INTO crt_crates
    VALUES(1, 'Crate 1');
    INSERT INTO crt_requests
    VALUES(1,'Request 1',1);
    INSERT INTO crt_materials
    VALUES(1,'Material 1', 1000);
    INSERT INTO crt_materials
    VALUES(2,'Material 2', 500);
    INSERT INTO crt_crate_bom
    VALUES(1,1,1,5);
    INSERT INTO crt_crate_bom
    VALUES(2,1,2,3);
    COMMIT;
    --So crate cost totals would be...
    SELECT cre_reference              request,
           ccr_name                   crate,
           SUM(cma_cost*ccb_quantity) crate_cost
    FROM   crt_requests,
           crt_crates,
           crt_materials,
           crt_crate_bom
    WHERE  cre_ccr_id = ccr_id
    AND    ccb_ccr_id = ccr_id
    AND    ccb_cma_id = cma_id
    GROUP BY cre_reference,
             ccr_name;
    --And request cost totals would be...
    SELECT cre_reference              request,
           SUM(cma_cost*ccb_quantity) crate_cost
    FROM   crt_requests,
           crt_crates,
           crt_materials,
           crt_crate_bom
    WHERE  cre_ccr_id = ccr_id
    AND    ccb_ccr_id = ccr_id
    AND    ccb_cma_id = cma_id
    GROUP BY cre_reference; Do you see what I mean - you don't store the derived values as they could get out of sync with the component parts that make then up. You derive them from the underlying data instead.
    Hope this makes sense.
    Cheers
    Ben

Maybe you are looking for

  • Can I partition a Firewire 800 drive to work with Time Machine and Final Cut Pro?

    Hey, I was reading that having Final Cut Projects and Events on the same external Hard Drive as a time machine backup doesn't work well together. So I was wondering if I partition a 2 TB External Hard Drive and use 1 partition for Time Machine and th

  • How can I move my iMovie app to "purchased" in my appstore account???

    how can I move my iMovie app to "purchased" in my appstore account???

  • How to get JBO error codes in infobus

    Hi, I am creating an Infobus based form. I am able to trap the errormessages generated by the system using the error manager. But I could get only the DAC error codes. I want to get the JBO error codes also, since they give more meaningful messages.

  • Oracle 10g on openSuSe 10.2

    hi, The limitation i have to work around is that /usr has only 30% space left on the server i am installing Oracle on. /opt however is configured with 30GB space and all apps/packages we use are only to be installed there so that is the partition i h

  • Current date minus 365 daqys

    In MS BI Query Designer I want to query the last 365 days from a DB2 table.  I can pull this data from Access, but can not figure out how to select the dataset for current date minus 365 days.  Here is what I have that works in Access select txn_date