Create procedure upsert (name of the existing table, incoming table name)

Is it possible to create a procedure that makes a merge (upsert) with only two parameters:

  1. Existing Table name - name of table that will have data merged into it.
  2. Incoming Table name - name of the table that has developed data day/news.

The method would be:

  1. Use primary keys on the "existing" table as the condition links
  2. Fact and update if exists and insert new
  3. no record
  4. no clues
  5. no removal clause

Oracle 11g

MERGE < tip > < table_name >

USING < table_view_or_query >

(< CONDITION >)

WHEN MATCHED THEN < update_clause >

DELETE < where_clause >

WHEN NOT MATCHED THEN < insert_clause >

[ERRORLOG < log_errors_clause > < reject limit < integer | unlimited >];

< table_name > - from input parameter

< table_view_or_query > -socket input parameter

< condition > - primary key links (how search a single/multiple primary keys and return the list?)

< update_clause > - update all columns (other than KP, how to get and use a dynamic list of columns)

< where_clause > - not used

< insert_clause > - insert new records for all columns (including the PK (s))

declare

p_source varchar2 (30): = "EMP_X";

p_target varchar2 (30): = "EMP_Y";

query varchar2 (32000);

function get_cols (p_table in varchar2) return varchar2 is

VARCHAR2 (32000) retval;

Start

Select the Group (order of column_id) listagg (column_name, ',')

in retval

of user_tab_cols

where table_name = p_table

Table_name group;

Return retval;

end;

function get_keys (p_table in varchar2) return varchar2 is

VARCHAR2 (4000) retval;

Start

Select listagg (cc.column_name, ',') in the Group (order by cc.position)

in retval

from user_constraints c,.

user_cons_columns cc

where cc.table_name = p_table

and c.constraint_type = 'P '.

and cc.table_name = c.table_name

and cc.constraint_name = c.constraint_name

C.table_name group;

Return retval;

end;

function merge (p_merge1 varchar2, p_merge2 varchar2, p_link varchar2) return varchar2 is

Merge1 varchar2 (32000): = p_merge1 | «, » ;

merge2 varchar2 (32000): = p_merge2 | «, » ;

VARCHAR2 (32000) retval;

Start

then merge1 is not null

loop

retval: = retval | » t.'|| substr (Merge1, 1, InStr (Merge1, ',') - 1) |'s =.' | substr (merge2, 1, InStr (merge2, ',') - 1);

Merge1: = substr (merge1, instr(merge1,',') + 1);

merge2: = substr (merge2, instr (merge2, ',') + 1);

If merge1 is not null then

retval: = retval | p_link;

end if;

end loop;

Return retval;

end;

Chopper (p_cols p_keys varchar2, varchar2) return varchar2 is

passes varchar2 (32000): = ', '. p_cols | «, » ;

keys varchar2 (32000): = ', '. p_keys | «, » ;

VARCHAR2 (32000) retval;

Start

While the keys! = «, »

loop

If instr (passes, substr (keys, 1, instr(keys,',',1,2))) = 1 then

cols: = substr (collars, instr(cols,',',1,2));

on the other

cols: = substr (passes, 1, instr (passes, substr (keys, 1, instr(keys,',',1,2))) | substr (collars, InStr (collars, ',', InStr (passes, substr (Keys, 1, InStr(Keys,',',1,2))), 2) + 1);)

end if;

keys: = substr (keys, instr(keys,',',1,2));

end loop;

return trim (both ',' collar);

end;

Start

query: = 'merge'. p_target |' t ' |' using (select ' | get_cols (p_source): ' from ' | p_source |') s '.

' on ('|) Merger (get_keys (p_target), get_keys (p_source), 'and') |') ' ||

"When matched then update set ' | '. Merger (Chopper (get_cols (p_target), get_keys (p_target)), Chopper (get_cols (p_source), get_keys (p_source)), ',').

«When not matched then insert ('|)» get_cols (p_target) |') values (s.'|) Replace (get_cols (p_source),', ', ', s') |') ';

dbms_output.put_line (Query);

end;


Fusion in EMP_Y t using (select EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO EMP_X) s on (t.EMPNO = s.EMPNO and t.ENAME = s.ENAME) when matched then update set t.JOB = s.JOB, t.MGR = s.MGR, t.HIREDATE = s.HIREDATE, t.SAL = s.SAL, t.COMM = s.COMM, t.DEPTNO = s.DEPTNO when not matched then insert (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO) values (s.EMPNO, s.ENAME, s.JOB, s.MGR, s.HIREDATE, s.SAL, s.COMM, s.DEPTNO)

Concerning

Etbin

Tags: Database

Similar Questions

  • Adding column not null in the existing table.

    How to add a column not null in the existing table?
    explain.
    Thank you
    create table abc_ex(a number);
    
    alter table abc_ex add(b number not null);
    
    desc abc_ex
    

    If for use then change to ALTER column extising

    Published by: nkvkashyap on May 27, 2013 21:49

  • Create ctxsys.ctxcat index in the object Table

    What I'm trying to do is to create an index of type ctxsys.ctxcat on 'col3 '. But this 'col3' is not a 'TABLE', but in an object, as follows:

    CREATE OR REPLACE TYPE TestObj AS OBJECT
    (
    col1 varchar2 (10),
    col2 varchar2 (10),
    COL3 varchar2 (10),
    COL4 varchar2 (10)
    );


    CREATE OR REPLACE TYPE AS THE TestObj TABLE TestTable;

    Now, how can I create an index of type ctxsys.ctxcat on 'col3 '?

    create index test_ind on TestTable (col3) indextype is ctxsys.ctxcat;?


    Thank you for helping.


    Scott

    You cannot index a user-defined data type. Indexes are used for persistent storage of persistent objects.

    What I suspect you really want is an associative array or an array indexed by integer binary. Demos here:

    http://www.morganslibrary.org/reference/arrays.html

  • Create table replaces the existing table in mssql

    In a program that allows us to update our sites, we use the function 'create an array' of MS SQL to create missing tables in databases.

    Thousands of time we used it, if a table already exists with the same name of the table in the create table MS SQL survey command an error.

    In fact, MS SQL documentation indicates that only if you include the optional 'replace' command, will be a replaced existing table.

    But today, we used this program on a new host, that we are trying, and the create table command actually did replace an existing table with a new table, delete all the records from the old table.

    I'm trying to understand what this would allow the settings at the server level.

    This is the code we use:

    < CFQUERY NAME = "recipe" DATASOURCE = "recipe" dbtype = "ODBC" username = "" #ruser # "password =" #rPASS #">"
    Create table recipecats)
    RecipecatID int IDENTITY(1, 1) NOT NULL PRIMARY KEY,
    recipecatdescription NVARCHAR (50) NULL)
    < / cfquery >

    Are you sure that this is not just to create another table with the same name, but one
    different owner?

    I saw the strangeness (it's probably just weird for me because I am ignorant)
    of what is happening), I can READ a table owned by another user without
    calling the name of the table with its owner, and when I go to CREATE a table
    of the same name, it is actually created as my current user and subsequently when
    you ask the name of the full table, I get the results of one, is not new
    the former. If I'm right in the name of the table, I can ask both/either. Kind
    way similar CF hunting around different scopes when you aren't eligible one
    reference to a variable.

    Also, your code should probably be testing to see if the table exists
    before you try to create it anyway. "Just try and catch.
    "If it errors" is not considered as 'test' if there is

    --
    Adam

  • Add the constraint not NULL in the existing table that has null values

    Hello

    I want to add a constraint not null to and an existing table, but the table already contains values null in this column.

    EMP

    Emp_id name

    1 axada

    2

    3 sdkdd

    Here is already the data IE 2 empid is Null as name. I must add a fool of constraint not null which new values will not be null, but I don't want to change the data of exisitng alreadt which is null.

    Hello

    "The opposite": NOVALIDATE does not validate the data that is ALREADY in the table, but do not allow the insertion of a NULL value.

    Have you tried my sample code?

    CREATE TABLE MaTable (x NUMBER PRIMARY KEY, y NUMBER);

    INSERT INTO myTable VALUES (1, 123);

    INSERT INTO myTable VALUES ( 2, NULL );

    INSERT INTO myTable VALUES (3, 456);

    ALTER TABLE mytable MODIFY (y NOT NULL NOVALIDATE );

    INSERT INTO myTable VALUES (4, 678);

    INSERT INTO myTable VALUES ( 5, NULL );

    SELECT * FROM MyTable;

    '2' line was inserted with null before the creation of the NOT NULL constraint, this line remains "as what" at the end of the trial.

    '5' line trying to insert a NULL value after creating the NOT NULL constraint, which is denied.

    Best regards

    Bruno.

  • Compress all the existing table ain dat

    Hello

    We use oracle 11.2.0.3 and wish to evaluate the performance of compression in terms of reduction of time takes to reports aganis the tables run.

    Had a quick serach and can see alter table compress but speaks only of data inserted/updated updated after the operationexecute of compress is compressed.

    Do not want to have to create a separate, compressed table and replace other table with that.

    Is it possible to compress all the existing dat aof existing table?

    Also could what kind of performance gain magntitudes we expect performance report using the compression compared to identical but uncompressed tabel?

    Also it is a data warehouse and the large fact table already has the default compressed index bitmpa.

    Tlamking on the compression of the table here.

    Thank you

    Published by: user5716448 on March 5, 2013 05:57

    Depending on your hardware, you can use alter table move and change the index on a table of size fairly decent rebuild in less than 10 minutes, but if you really make the look works online in the dbms_redefinition package. See the manual of the PL/SQL Package and Types, then look at the note support for Oracle at the following address:

    Master note: an overview of redefining online tables (DBMS_REDEFINITION) [ID 1357825.1]

    HTH - Mark D Powell.

  • Create variable FileGlobals without deleting the existing, using the API of TestStand, LabVIEW

    Dear community OR,.

    I create the FileGlobals Variables as described in the attachments. Variables are created, but at the same time, all the existing ones if the FileGlobals file is deleted. Could someone help, please, how can I insert variables, no effect on already existing ones?

    Thank you very much in advance!

    I struggled with this problem all morning, and... I realized that this code does not remove the FileGlobals variables. Code to create the fact, that runs before this code... So I corrected the code - it works now!

    Thanks for all the help, I found interesting things of couple - I did not know this increment of the changes made to the file.

  • Adding data to the existing Table

    Hello..

    IAM, try to import the oracle dump file. but the tables in dump files already exist in my database. How can I add data to existing tables... pls suggest me.

    Thank you.

    You don't say what you use the tool...

    If you use the traditional import utility (imp) then you can tell him to ignore the fact that there is already a table: IGNORE = Y.

    And I can't import datapump has similar features.

  • Report Generation Toolkit - keep the existing table

    Previously, I used the TXT (CSV) files to store test data. Some tests to run for 1000 hours and collect anywhere from a few lines of thousands of data from more than 100,000 rows of data. Using this approach, I have to write macros VBA to parse and format of these data, which are very time-consuming. I'm looking to try to use the LabVIEW Toolkit for generation report (GTA) to write directly in an Excel spreadsheet and do some steps on the fly as the VBA macro, to help reduce the processing time and manual work on the analysis of the data.

    However, my concern is that sometimes one must quit school essay through a long trial and then continue and add data to the existing data. I don't see how using the GTA. I guess you would have to locate the latest data from the spreadsheet... using a TXT file, LabVIEW is done automatically. In Excel, I use VBA code like this:

    RowMax is SheetRD.Cells ("A", SheetRD.Rows.Count). End (xlUp) .row

    The GTA has features like that, or I'll have to call a macro and then work with the returned value of RowMax?

    You can use Excel get last Row.vi of the specific generation of report-> Excel-> General Excel palette. Add 1 to get the line empty next.

    Ben64

  • Creating a filter for the existing table

    Hello

    I have a table and initially I didn't intend to use the filter on the table... but due to needs sudden I have to add the filter to the table and I can not afford to recreate the table.
    My version of jdev is 11.1.1.6

    Thank you
    Tarun

    Hello

    Add the property
    -filterModel
    -sortProperty
    -filterable = true

                  
                    
    

    concerning
    Peter

  • View of the existing tables logic model

    Hello!

    I'm new to the Oracle sql developer Data Modeler.

    I use Version 2.1.1.64 of the oracle sql developer.

    I've created connections to a scheme called "you".

    I use this pattern for my development with apex 4 and oracle 10g xe.

    For an application, I use this schema tables (I created these table with apex).

    Now, I want to display the model logical and physical this tables with oracle sql developer Data Modeler.

    I have not found a tutorial how to do this.

    And I have no idea how start up!

    Can someone help me?

    Thank you!

    Gerhard

    I would recommend oyu get the most recent version. You can import existing templates using older versions of the Data Modeler but I don't know if it's available through SQL Developer in earlier versions.

    I don't not know umbutu so help oyu it. For windows, that you just download the file and unzip it. When you start the exe file it will automatically migrate your connections.

  • ORA-08103 export newspaper despite the existing table

    Hi all

    my database is on oracle 11G.


    I ran a backup of my database of production export and I met the following exception error in my log:

    . . export of table TABLE_NAME_1234
    EXP-00056: ORACLE error 8103
    ORA-08103: object no longer exists

    I logged in my database to see that this table, TABLE_NAME_1234 exists.


    the error indicates that the object no longer exists...

    What could be the reason?


    Thank you

    KK

    May be at the start of the export of the table, the table has been truncated by some other session in the database.

    Can you try to resume the export and return.
    Anand

    Published by: Anand... on October 12, 2010 11:52

  • list by commas must be build as a table using the existing table column

    Hi all

    I have table with a comma separate value, column container

    Select 1 emp_id, edu 'BSc, MCA' double

    Union of all the

    Select 2 Emp_id, 'b.SC., MBA' double

    Union all

    Select 3 Emp_id, 'Bsc, MEd' of the double

    and I need to replace as follows

    Emp_id edu

    1                  BSc

    1                  MCA

    2                  BSc

    2                  MBA

    3                  Bsc

    3                  MEd

    How to achieve...

    Iqbal

    Notes on the Oracle: split delimited by a comma the way of RegExp string, second part

  • How to create a new page with the existing provision of the one that I already created?

    Well, I'm very new to DreamWeaver, just an info. I was ordered to develop a site for a company. There will be as a total of 10 pages on the site. I created the home page, and I'm now trying to make the other. But I don't know how I can take the basic layout, I created in the homepage so I can add information for other pages later. I tried to save as a template, but I had to create editable regions and those got in the way. I even tried to copy the code from the original, but then the Spry menus will not work correctly. I hope I passed my problem properly. Any help will be more useful.

    Thank you.

    1. Open index.html
    2. File > save as > page2.html
    3. Repeat for other pages of the site...
    4. Change content as needed.

    Nancy O.

    ALT-Web Design & Publishing

    Web | Graphics | Print | Media specialists

    http://ALT-Web.com/

    http://Twitter.com/ALTWEB

    http://ALT-Web.blogspot.com/

  • steps to create the new table using existing metadata

    Hi all


    That's what I want to achieve,

    I want to create a procedure that will take an input parameter as a table name lets say 'EMP ',.
    This procedure checks if this table exists or not?
    If they don't exist
    It will create a new table with the name _dummy join the existing table name (ex: new table will be EMP_DUMMY).
    and new table should have the same structure of the table, indexes, and constraints on the EMP table.


    NB: It should not be created using select as create table EMP_DUMMY select * from EMP where = condition false;



    Can someone help me please how to achieve this?

    Please, don't post duplicate discussions.

    Check your thread previous stored procedure to create a new table with the existing table structure to further discussions

Maybe you are looking for