How to delete row by row comparing to first collumn?

Hello!
I have a problem - I need to delete row by row , but the problem is, that I know that first COLUMN of any table is a PK.
To retrieve COLUMN NAME I use:
SELECT column_name, table_name FROM USER_TAB_COLUMNS WHERE column_id = 1 and table_name = c1.tmp_table_name;
But this somehow doesn't work.
Below you can see my script (not worked for now):
declare
xxx varchar2(100);
begin
for c1 in (select table_name, tmp_table_name from tmp_tables) loop
EXECUTE IMMEDIATE
' SELECT column_name into '|| xxx ||' FROM USER_TAB_COLUMNS WHERE column_id = 1 and table_name = ' ||''''||c1.tmp_table_name||'''';
execute immediate
'begin
for c2 in (select * from '|| c1.tmp_table_name || ') loop begin
insert into '|| c1.table_name || ' values c2; delete from '|| c1.tmp_table_name || ' where ' || xxx ||' = c2.'||xxx ||'; exception when others then null; end; end loop; end;';
end loop;
end;
P.S. Inserts work perfect. I have a problem with delete rows that are in c1.table_name, from c1.tmp_table_name (this two tables have the same structure, PK, always), because I have different column names in another tables tables that are PK. (for example: K, ID, NS and so on) please help me to write correct script.
For example for first fetched row it will be like:
begin
for c1 in (select table_name, tmp_table_name from tmp_tables) loop
execute immediate
'begin for c2 in (select * from '|| c1.tmp_table_name || ') loop begin
insert into '|| c1.table_name || ' values c2; delete from '|| c1.tmp_table_name ||' where K = c2.K; exception when others then null; end; end loop; end;';
end loop;
end;
That script works perfect. But I have many others tables with different PK - not K.

Solution with error-logging table
-- create the error-logging table
CREATE TABLE tbl_MergeErrors (
    Stamp       TIMESTAMP(3),
    TableName   VARCHAR2(30),
    KeyColumn   VARCHAR2(30),
    KeyValue    VARCHAR2(4000),
    ErrorCode   NUMBER(5),
    ErrorMsg    VARCHAR2(4000),
  CONSTRAINT pk_MergeErrors
      PRIMARY KEY (TableName, Stamp)
      USING INDEX
-- procedure to insert errors
CREATE OR REPLACE
PROCEDURE LogMergeError (pTableName  IN VARCHAR2,
                         pKeyColumn  IN VARCHAR2,
                         pKeyValue   IN VARCHAR2)
IS PRAGMA AUTONOMOUS_TRANSACTION;
    -- you couldn't insert SQLCODE or SQLERRM directly into a table (ORA-00984)
    nSQLCODE   NUMBER(5)      := SQLCODE;
    vcSQLERRM  VARCHAR2(4000) := SQLERRM;
BEGIN
  INSERT INTO tbl_MergeErrors
         (Stamp, TableName, KeyColumn, KeyValue, ErrorCode, ErrorMsg)
      VALUES (SYSTIMESTAMP, RTrim( SubStr( pTableName, 1, 30)),
              RTrim( SubStr( pKeyColumn, 1, 30)), SubStr( pKeyValue, 1, 4000),
              nSQLCODE, vcSQLERRM);
  COMMIT WORK;
-- if an error occured here, then just roll back the autonomous transaction
EXCEPTION
  WHEN OTHERS THEN   ROLLBACK WORK;
END LogMergeError;
-- create the tables and insert test-data
CREATE TABLE TMP_TABLES (
    TABLE_NAME       VARCHAR2(200),
    TMP_TABLE_NAME   VARCHAR2(200),
  CONSTRAINT TMP_TABLES_X PRIMARY KEY (TABLE_NAME)
CREATE TABLE TMP_KL002 (
    K   VARCHAR2(40),
    N   VARCHAR2(200)
CREATE TABLE TMP_TABLE1 (
    NS   VARCHAR2(40),
    N    VARCHAR2(200)
CREATE TABLE KL002 (
    K VARCHAR2(40),
    N VARCHAR2(200),
  CONSTRAINT PK_KL002 PRIMARY KEY (K)
CREATE TABLE TABLE1 (
    NS   VARCHAR2(40),
    N    VARCHAR2(200),
  CONSTRAINT PK_TABLE1 PRIMARY KEY (NS)
INSERT INTO TMP_TABLES (TABLE_NAME, TMP_TABLE_NAME) VALUES ('kl002','tmp_kl002');
INSERT INTO TMP_TABLES (TABLE_NAME, TMP_TABLE_NAME) VALUES ('table1','tmp_table1');
INSERT INTO tmp_KL002 (K, N) VALUES ('00', 'none');
INSERT INTO tmp_KL002 (K, N) VALUES ('07', 'exists');
INSERT INTO tmp_KL002 (K, N) VALUES ('08', 'not assigned');
INSERT INTO tmp_table1 (NS, N) VALUES ('2000', 'basic');
INSERT INTO tmp_table1 (NS, N) VALUES ('3000', 'advanced');
INSERT INTO tmp_table1 (NS, N) VALUES ('4000', 'custom');
COMMIT WORK;
-- to test, if it works correct when primary key values exists before
INSERT INTO KL002 VALUES ('07', 'exists before');
COMMIT WORK;
-- check the data before execution
SELECT * FROM TMP_KL002 ORDER BY K;
SELECT * FROM KL002 ORDER BY K;
SELECT * FROM TMP_TABLE1 ORDER BY NS;
SELECT * FROM TABLE1 ORDER BY NS;
-- empty the error-logging table
TRUNCATE TABLE tbl_MergeErrors DROP STORAGE;
-- a solution
DECLARE
    PLSQL_BLOCK  CONSTANT VARCHAR2(256) := '
BEGIN
  FOR rec IN (SELECT * FROM <0>) LOOP
    BEGIN
      INSERT INTO <1> VALUES rec;
      DELETE FROM <0> t WHERE (t.<2> = rec.<2>);
    EXCEPTION
      WHEN OTHERS THEN
          LogMergeError( ''<1>'', ''<2>'', rec.<2>);
    END;
  END LOOP;
END;';
BEGIN
  FOR tabcol IN (SELECT t.Tmp_Table_Name, t.Table_Name, c.Column_Name
                 FROM Tmp_Tables t,
                      User_Tab_Columns c
                 WHERE     (c.Table_Name = Upper( t.Tmp_Table_Name))
                       AND (c.Column_ID = 1)
            ) LOOP
    EXECUTE IMMEDIATE Replace( Replace( Replace( PLSQL_BLOCK,
                               '<0>', tabcol.Tmp_Table_Name),
                               '<1>', tabcol.Table_Name),
                               '<2>', tabcol.Column_Name);
  END LOOP;
END;
-- check the data after execution ...
SELECT * FROM TMP_KL002 ORDER BY K;
SELECT * FROM KL002 ORDER BY K;
SELECT * FROM TMP_TABLE1 ORDER BY NS;
SELECT * FROM TABLE1 ORDER BY NS;
-- ... and also the error-logging table
SELECT * FROM tbl_MergeErrors ORDER BY Stamp, TableName;
-- of couse you must issue an COMMIT (the ROLLBACK is only for testing
ROLLBACK WORK;
-- drop the test-tables
DROP TABLE TABLE1 PURGE;
DROP TABLE KL002 PURGE;
DROP TABLE TMP_TABLE1 PURGE;
DROP TABLE TMP_KL002 PURGE;
DROP TABLE TMP_TABLES PURGE;
-- you shouldn't drop the error-logging table, but I use it to free up my db
DROP TABLE tbl_MergeErrors PURGE;Greetings, Niels

Similar Messages

  • How to delete rows in the target table using interface

    hi guys,
    I have an Interface with source as src and target as tgt both has company_code column.In the Interface i need like if a record with company_code already exists we need to delete it and insert the new one from the src and if it is not availble we need to insert it.
    plz tell me how to achieve this?
    Regards,
    sai.

    gatha wrote:
    For this do we need to apply CDC?
    I am not clear on how to delete rows under target, Can you please share the steps to be followed.If you are able to track the deletes in your source data then you dont need CDC. If however you cant - then it might be an option.
    I'll give you an example from what im working on currently.
    We have an ODS, some 400+ tables. Some are needed 'Real-Time' so we are using CDC. Some are OK to be batch loaded overnight.
    CDC captures the Deletes no problem so the standard knowledge modules with a little tweaking for performance are doing the job fine, it handles deletes.
    The overnight batch process however cannot track a delete as its phyiscally gone by the time we run the scenarios, so we load all the insert/updates using a last modified date before we pull all the PK's from the source and delete them using a NOT EXISTS looking back at the collection (staging) table. We had to write our own KM for that.
    All im saying to the OP is that whilst you have Insert / Update flags to set on the target datastore to influence the API code, there is nothing stopping you extending this logic with the UD flags if you wish and writing your own routines with what to do with the deletes - It all depends on how efficient you can identify rows that have been deleted.

  • How Are Deleted Rows Tracked in Text Index?

    Does the database track this information in a table, or does it modify the record in the $I table and mark it as deleted. Just doing some analysis on an index that hasn't had the full optimization done to it in a while and want to know how I can get a count of deleted rows before I optimize so that I can troubleshoot this better in the future. Thanks!!

    Hi ,
    deleted documents are tracked in $N table. Use ctx_report.index_stats procedure to get more details about index fragmentation.
    Thanks,
    Edwin

  • How to Delete rows in the database table by using Table Control

    Hi Experts,
    I wrote one program.
    In that program i used table control.
    I displayed data from database table in the table control, but i want to delete selected rows.
    Can anybody please tell me this by writing sample code
    thank you
    Basu

    Hi ,
    Pls try this coding below or check the prg demo  - RSDEMO02 in se38
    WHEN 'DELL'.
    * remove marked lines
          LOOP AT IT_SPFLI WHERE MARKED = 'X'.
            DELETE IT_SPFLI.
          ENDLOOP.
          IF SY-SUBRC <> 0.
            GET CURSOR FIELD FLD LINE LINNO OFFSET OFF.
            SET CURSOR FIELD FLD LINE LINNO OFFSET OFF.
            IF FLD CP 'IT_SPFLI*' AND SY-SUBRC = 0.
              LINNO = LINNO + TC_SPFLI-TOP_LINE - 1.
              DELETE IT_SPFLI INDEX LINNO.
              TC_SPFLI-LINES = TC_SPFLI-LINES - 1.
            ENDIF.
          ENDIF.
    or another eg :
    MODULE USER_COMMAND_0100 INPUT.
        SAVE_CODE = OK_CODE.
        CLEAR OK_CODE.
        CASE SAVE_CODE.
    WHEN 'DELE'.
                CALL FUNCTION 'COPO_POPUP_TO_GOON'
                    EXPORTING
                         TEXTLINE1 = 'Selected rows will be deleted!'
                         TEXTLINE2 = 'Are you sure?'
                         TITEL     = 'Delete rows'
                    IMPORTING
                         answer    = confirmation.
                IF CONFIRMATION = 'G'.
                    REFRESH ITAB_PHONELIST.
                    CLEAR ITAB_PHONELIST.
                ENDIF.
    MODULE EXTRACT_USERDATA INPUT.
        CASE SAVE_CODE.
            WHEN 'DELE'.
                IF SELECTION IS INITIAL AND
                   confirmation = 'G'.
                     CLEAR ITAB_PHONELIST.
        ITAB_PHONELIST-NAME = RECORD-NAME.
        ITAB_PHONELIST-PHONE = RECORD-PHONE.
        ITAB_PHONELIST-EMAIL = RECORD-EMAIL.
        APPEND ITAB_PHONELIST.
    <b>Reward pts if found usefull :)</b>
    regards
    Sathish

  • How to delete the icloud account of the first owner of my ipad it need password.

    APPLE IPAD MINI  PART NO. MD528LL/A   16 GB WIFI   MODEL : A1432
    OPERATING SYSTEM: IOS 8..1.2
    WE GOT THIS ITEM IN A NON APPLE STORE FOR $150.00 ONLY- I AM A SECOND HAND OWNER.
    MY CONCERN IS , I CAN NOT DELETE THE  ICLOUD ACCOUNT OF THE FIRST OWNER , I HAVE LIMITED ACCESS BECAUASE  IT ALWAYS REQUIRES PASSWORD OF THE FIRST OWNER, I NEED HELP TO DELETE THE ACCOUNT.
    IM SO HAPPY IF ANYBODY COULD SHARE TO ME..

    You must contact the previous owner to have them remove the Activation Lock. There is no way around this. Here are two links. One explains the Activation Lock, and the second one explains what the previous owner needs to do to remove it for you:
    ACTIVATION LOCK
    Find My iPhone Activation Lock: Removing a device from a previous owner’s account - Apple Support
    Best of luck,
    GB

  • How to delete rows from 2D array in this case...

    Hello. I'm just begging adventure with labview so please for patient. I created a program whitch suppose work in following way:
    2D Input array is array created by FOLDER BROWSING subVI. It works in this way,that browse folder and looking for txt files whose contanins measurment data. In my case subVI founds 4 files,and from theirs headers read information about what kind of data are in file also their's path. In this way is created 2D Input Array. subVI named PLOTS FROM PATHS ARRAY make picture with polar/XY plot. It's create only those plots and legends on one picture as many files(their paths) is setted to the program by output array. I made this subVI in that way and I would not like to change it. 
    My problem is that in even loop (witch check for any change by user) program suppose to relay anly those rows(files) for which checkbox are marked, e.g. marking anly 1 and 4 box, program should chose from input array row 1 and 4 only and pass them to output array,then  PLOTS FROM PATHS ARRAY subVI makes a picture only with 1 and 4 plot and legend only for plot 1 and 4. The best solution would be some relay witch is avtivated by logical signal. It lost to me ideas how to solve it, I'm just in blaind corner...
    I tried to use delete from array but I don't know how to do use it properly in this program,becease it can be only before or afeter for loop. Below is scan of front panel and also main problem. Please set me up somehow to solve this problem. 
    Regards 
    Solved!
    Go to Solution.
    Attachments:
    plots selector.vi ‏17 KB
    problem.PNG ‏18 KB

    I have attached a vi. Is this the one that you need?
    Anand kumar SP
    Senior Project Engineer
    Soliton Technologies Pvt Ltd
    Attachments:
    plot selector modified.vi ‏14 KB

  • Add Column Delete  in report, How to delete row using this delete Option

    Hi Friends,
    i have a report ,iwant to add an option DELETE in last column.When i click on DElete then respective id sholund be deleted.
    My Table Is
    CREATE TABLE  "DUMY_FILE"
       (     "ID" NUMBER,
         "NAME" VARCHAR2(500),
         "FILE_OBJ_ID" NUMBER,
         "MIME_TYPE" CLOB,
         "DOC_SIZE" NUMBER,
         "BLOB_CONTENT" BLOB,
         "DESCRIPTION" VARCHAR2(500),
         "UPLOAD_DATE" CHAR(25)
    How can i do this.
    Thanks
    Edited by: 805629 on Nov 16, 2010 11:51 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Trent,
    Thanks for you suggestions. .. Let me explain my problem a little better ...
    I have a report that lists fields associated with a report ... I have a delete icon which deletes a row and removes it from the underlying table ... however, I am trying to implement a Before header process which runs a pl/sql process that checks if the selected field is the last field in the report ... if so, I want a confirmation dialog to pop up ... if they click cancel .. then the deletion is aborted, else the field is deleted (which triggers other status changes).
    Based on this logic if there is a way to implement this based on your suggestion I would appreciate it ...
    Here is the process I was trying to use .... but the I have a few issues with this approach
    declare
    -- cursor to check if this is the last field
    cursor fld_cnt is
    select count(*) from prm_ptnr_rpt_fields
    where report_uid = :P22_REPORT_UID;
    num_flds number;
    msg varchar2(300);
    begin
    open fld_cnt;
    fetch fld_cnt into num_flds;
    If num_flds > 1 then
    delete from prm_ptnr_rpt_fields
    where report_uid = :P22_REPORT_UID
    and field_user_key = :P9_DELETED_FLD;
    commit;
    :P9_DELETED_FLD := NULL;
    msg := :P9_FIELD_NAME || ' Field Excluded From Report' ;
    apex_application.g_print_success_message := msg;
    else
    htp.p('<script type="text/javascript">');
    htp.p('
    var r=confirm("This is the last field included in this report .. \n Deleting it will Inactivate the report and remove it from schedule (if scheduled) ...\n Do you want to proceed?");
    if (r==true)
    {      delete from prm_ptnr_rpt_fields 
    where report_uid = :P22_REPORT_UID
    and field_user_key = :P9_DELETED_FLD;
    :P9_DELETED_FLD := NULL;
    commit;
    msg := :P9_FIELD_NAME || ' Field Excluded From Report' ;
    update prm_ptnr_rpts
    set report_status = 'INCOMPLETE',
    active_report = 'N'
    where report_uid = :P22_REPORT_UID;
    msg := msg || ' and Report Status changed to INCOMPLETE';
    apex_application.g_print_success_message := msg;
    htp.p('}else {
    alert("Delete Action Aborted");
    htp.p('</script>');
    End if;
    Close fld_cnt;
    end;
    a) Even if I click cancel ... the field still gets deleted ...
    b) :P9_DELETED_FLD is the id for the selected field ... I am setting it on the link attributes which places it on the URL ... I would rather user javascript (but not exactly sure how).
    Thanks,
    Gerald
    Edited by: user5459177 on Feb 22, 2011 2:45 PM

  • How to delete row in listbox with formatting

    Hello, I have a listbox and I want to delete selected rows (by clicking button in the example). It deletes the rows just fine but the problem is that I also want to preserve formating of the items when they are moved. The only way is to copy the formating programatically which is incredibly s  l  o  w. Even if I defer panel updates it takes second to delete 20rows and reformat the rest. Do u have anybody any idea how to do that in more usable way? Thanks!!!
    Message Edited by ceties on 07-17-2009 06:44 AM
    LV 2011, Win7
    Attachments:
    DeleteRowsPreserveFormatting.vi ‏38 KB

    Hi Ceties,
    You are right that deffering front panel in
    this case doesn't help so much.  This is because Multiconumn Listbox
    doesn't use Synchronous Display by default. If you set to use
    synchronous display, and you wouldn't deffer front panel updates, your
    performance would be significantly wors. 
    With attached
    example, to erase one row, when I set different formatting for each
    cell, it takes about 0.6s on my computer to finish. With Synchronous
    Display it takes more than 6s !, so you could see great difference.
    Moreover,as you can see, I read all the time actual formatting. this
    reading takes about 0.20s itself. If you avoid reading it all the time,
    and instead you will keep it in memory, you can save somethink like 30%
    of the time!
    In case you need to update each
    cell font separately,  you need to update a lot of cells. In our case
    it is about 2000 property node calls. Positive think is, that more
    cells you delete, faster theoperation is
    Anyway, I
    belive that it is not very important to keep all the data in the table.
    If the performance is of the question, I would keep all data in memory
    in shift registers for example, and I would all the time display just
    reasonable amount of data in listbox. You can implement scrolling by
    your self, and thus you could keep just couple of hundred rows
    displayed.However, this would give another challange to update all the
    time formatting as you scroll
    At
    the last, I believe that with good architecture it should not be
    problem to update those data in table from different locations. It can
    just take some more time to develop your code  
    Use just useful advices
    Martin
    Attachments:
    Copy of DeleteRowsPreserveFormatting-3.vi ‏63 KB

  • How to delete rows from multiple tables when pressing button

    Hi, I'm wondering how do I delete a row from two different tables at the same time when I press the Delete button. Both tables have GROUP_ID as their primary key.

    Nevermind! I realized that I had "reset" before my process to delete from the 2nd table.

  • How to delete row of old emails appearing on top line of thunderbird(i cant get to inbox without scanning tens of old emails)

    on top row of t-bird is a list of old emails. in order to get to the new emails (inbo) i have to delete hundreds of old emails. by going by all the old stuff to get to the inbox (new emails)

    If you are talking about all the old tabs where you have opened, read and failed to close the message tab, right click one of them and select Close Other Tabs. Then use the x to close the last one. Now learn to close a message tab after you read the message.

  • How to delete rows in the SQL Server table based on the contents of Excel file

    Hello, everyone,
    I have an Excel file which contains data for certain dates. I need to load it in a SQL Server table. But before doing that, I need to check if the table already contains data for the dates in the Excel file. If it does, I need to delete those data
    first. Not sure what is the best and efficient way to do this. Your help and guidance would be much appreciated.
    Thank you in advance.

    there are multiple ways of doing this
    Fastest method would be below
    1. Have a data flow task using excel source. Then add a OLEDB destination to dump the data to a staging table
    2. Have a Execute sql task to delete data from your actual table based on staging table data. The query would look like
    DELETE t
    FROM YourTable t
    WHERE EXISTS (SELECT 1
    FROM StagingTable
    WHERE DateField = t.DateField)
    3. Have another execute sql task to do final insert like
    INSERT YourTable (Col1,Col2,...)
    SELECT Col1,Col2,..
    FROM StagingTable
    the above operations will be set based and faster
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • How to delete and add rows in a table control

    Hi
      how to delete rows and add new rows in a tbale control
    Sathya

    Hi,
    In the PAI write this code
    PROCESS AFTER INPUT.
    LOOP AT itab.
    ENDLOOP.
    MODULE MODIFY_TC.
    MODULE MODIFY_TC.
    To add a row
      DESCRIBE TABLE itab LINES tc_tab-lines.
      tc_tab-lines = tc_tab-lines + 1.
    To delete a row if check box is ticked
       DELETE itab WHERE check = c_x.
    To delete a row depending on tabix
       DELETE itab index l_tabix.
    ENDMODULE.
    Make sure that you put a if condition in the above module inorder to ensure addition or deletion of a row.
    Best regards,
    Prashant

  • Deleting rows from a table

    COuld anyone tell me how to delete rows from a table which has millions of rows.
    TIA,
    Oracle user

    if you are deleting all the rows, use "truncate table" in sql*plus.
    or if you are deleting all but a handful of rows, then copy the rows you still want to a spare table, drop the original table, and rename the spare table back to the original table's name.
    hope this helps

  • Delete rows from Tabular form

    Hi,
    Anyone knows how dynamicly delete rows from Tabular Form (on button click, button is as item)?
    Thanks.

    I am in a great fix. We had a test instance.. and we had a version apex 3.2.. But when the same application has been uploaded to prod.. we used apex 4.0.Why on Earth would you do this? The whole point of the testing is to verify that the application will work in the production environment: the first requirement for this is that the test and production environments are equivalent.
    has any body is facing the same issue as mine..Yes, as is easily discovered by searching the forum...see Delete button doesn't work in tabular form after upgrade from APEX3.2 to 4.

  • How to delete in backend?

    Hi all,
           How to delete rows in backend by using webdynpro java?
           Please provide code?
    Regards,
    Srini

    Hi Srinivasulu,
    First you will have to import the BAPI into the web dynpro component.
    Add the model to the used models of the component.
    Create a binding between the model and component controller.
    In the component controller instaniate the model class and bind it to the model node.
    Create a method for the execution of the bapi.
    You can access the following link for more information on how to call RFCs from Web Dynpro:
    https://www.sdn.sap.com/irj/scn/go/portal/prtroot/docs/library/uuid/10c2c440-7f8c-2b10-7db0-dce34360f118
    In your case you can have a single model and import all the BAPIs in the same model.
    Create the binding between the component controller and model. Create the model nodes for the BAPIs.
    Create methods to execute the BAPIs.
    On the action like approve or reject or save, parameters of the BAPI are set in the model node and the method which executes the required BAPI is called.
    Regards,
    Kartikaye

Maybe you are looking for