How to Insert a data along with update on same duplicate record - oracle

I want to insert a one or more records in table A.
But same record already existing in records with status Active
CREATE PROCEDURE Test
AS
BEGIN
INSERT INTO A (x,y,z,status)
SELECT data FROM A WHERE some condtion;
... Here i want to update table A status column into 'N', if the inserted data already existing in table A Compared with x,y,z column.
EXCETION
---Handled
END;

You can try this:
MERGE INTO target_table t
USING source_table s
ON (t.id = s.id)
WHEN MATCHED THEN
UPDATE SET t.col1 = s.col1
WHEN NOT MATCHED THEN
INSERT (col1, col2) VALUES (s.col1, s.col2);
Documentation Link: https://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_9016.htm#SQLRF01606

What you probably want to do is a merge-statement. The merge statement checks if the dataset already exists. In this case you can formulate an update statement. For example, you could update the status. If not, the new dataset will be inserted.
For further information you should hava a look here.

The merge is the way to go. Another approach is first updating all the rows that match the criteria and after do the insert.
However, if your problem is how to differentiate the 2 rows, use the pseudo-column ROWID.

Related

How to make insert statement re-runnable?

Need to add two following insert statements:
insert into table1(schema, table_name, table_alias)
values ('ref_owner','test_table_1','tb1');
insert into table1(schema, table_name, table_alias)
values ('dba_owner','test_table_2','tb2');
Question is how can I make those two insert statements re-runnable meaning, if those two insert statement are compiled again, it should throw row exists error or something along those lines...?
Additional notes:
1. I've seen examples of Merge in Oracle however, thats only when you're using two tables to match records. In this case im only using a single table.
2. The table does not have any primary, unique or foreign keys - only check constraints on one of the columns.
Any help is highly appreciated.
You can use a MERGE statement, as follows:
MERGE into table1 t1
USING (SELECT 'ref_owner' AS SCHEMA_NAME, 'test_table_1' AS TABLE_NAME, 'tb1' AS ALIAS_NAME FROM DUAL
UNION ALL
SELECT 'dba_owner', 'test_table_2', 'tb2' FROM DUAL) d
ON (t1.SCHEMA = d.SCHEMA_NAME AND
t1.TABLE_NAME = d.TABLE_NAME)
WHEN NOT MATCHED THEN
INSERT (SCHEMA, TABLE_NAME, TABLE_ALIAS)
VALUES (d.SCHEMA_NAME, d.TABLE_NAME, d.ALIAS_NAME)
Best of luck.
You should have a primary key, especially when you want to check for duplicate records and data integrity.
Provide a primary key for your table, or, if you somehow do not want to do that, create a unique constraint for all of the columns in the table, so no duplicate rows are possible.

Redirect duplicate rows to update while insert

I have a insert statement on table "test". PK on column x in the table "test".
Now while inserting if duplicate row comes then the same row should get updated instead insert.
How can i achieve this.
Is it possible by dup_val_on_index?
Please help.
First create a copy of the above table without any KEY Columns and follow
Step 1: truncate the table first whenever you encounter a bunch of insert statement comes
Step 2: INSERT the above truncated tables
Step 3: Execute the MERGE statement like below
MERGE INTO TABLE_MAIN M
USING TABLE_MAIN_COPY C
ON (m.id = c.id)
WHEN MATCHED THEN UPDATE SET M.somecol = c.somecol
WHEN NOT MATCHED THEN INSERT (m.id, m.somecol)
VALUES (c.id, c.somecol);
You may incur error while on merger ORA-30926: unable to get a stable set of rows in the source tables when there is two or more rows while on update.
you may avoid that using the GROUP function related to id or like ORA-30926: unable to get a stable set of rows in the source tables

Oracle Trigger UPDATE instead of INSERT

Trying to find a way to write an Oracle trigger that would check before an insert to see if a match was found in the primary column and if so update the row information instead of inserting a new row.
I've looked at before insert. Is there a way to cancel the insert based on criteria inside that block?
I've also looked at using the instead of clause but it requires working on a view.
What is the best way to go about this?
Use a MERGE statement instead of an INSERT.
Use a merge statement.
MERGE INTO <<your table>> t
USING (<<your list of records - can be the result of a SELECT >>)
ON ( <<join between table and list of records >>)
WHEN MATCHED THEN
UPDATE SET << the rows you want to set>>
WHEN NOT MATCHED THEN
INSERT (<<columns of table>>)
VALUES (<<value>>)
https://oracle-base.com/articles/9i/merge-statement

Conditional Insert or Update in Oracle

I have one table in oracle where data gets inserted from some third party. I want to populate master tables from that table. So, what will be the best way performance wise using collection.
E.g. Suppose, the table into which data will get populated from third party is 'EMP_TMP'.
Now I want to populate 'EMPLOYEE' master table through procedure which will get populated from EMP_TMP Table.
Here again there is one condition like IF SAME EMPID (this is not primary key) EXISTS then we have to UPDATE FULL TABLE which consists of SAME EMPID ELSE we have INSERT NEW RECORD.
[Note: Here EMPID is VARCHAR2 and EMPNO will be primary key where we will use SEQUENCE]
I think here merge will not perform much better performancewise since we cant use collection in MERGE statement.
Well, if performance is your primary consideration, and you don't like MERGE, then how about this (run as script, single transaction):
delete from EMPLOYEE where emp_id IN (
select emp_id from EMP_TMP);
insert into EMPLOYEE
select * from EMP_TMP;
commit;
Obviously not the "safest" approach (and as written assumes exact same table definitions and you have the rollback), but should be fast (you could also mess with IN vs EXISTS etc). And I couldn't quite understand your post if emp_id or emp_no was the common key in these 2 tables, but use whichever makes sense in your situation.
Create a procedure, you need to be using PL/SQL.
Do an update first then test sql%rowcount.
If it is 0, no updates where done and you have to do an insert instead.
I think that this is fairly efficient.
pseudo code
Update table;
if sql%rowcount = 0 then
//get new sequence number
insert into table;
END IF;
COMMIT;
HTH
Harv

Insert into oracle database

Hi I have a database with loads of columns and I want to insert couple of records for testing, now in order to insert something into that database I'd have to write large query .. is it possible to do something like this
INSERT INTO table (SELECT FROM table WHERE id='5') .. I try to insert the row with ID 5 but I think this will create a problem because it will try to duplicate a record, is it possible to change this ID 5 to let say 1000 then I'd be able to insert data without writing complex query and while doing so avoiding replication of data .. tnx
In PL/SQL you can do something like this:
declare
l_rec table%rowtype;
begin
select * into l_rec from table where id='5';
l_rec.id := 1000;
insert into table values l_rec;
end;
If you have a trigger on the table to handle the primary key from a sequence (:NEW.id = seq_sequence.NEXTVAL) then you should be able to do:
INSERT INTO table
(SELECT columns_needed FROM table WHERE whatever)
This will allow you to add in many rows at one (the number being limited by the WHERE clause). You'll need to select the columns that are required by the table to be not null or not having default values. Beware of any unique constraints as well.
Otherwise you'll be looking at PL/SQL or some other form of script to insert multiple rows.
For each column that has no default value or you want to insert the values other than default, you will need to provide the explicit name and value.
You only can use an implicit list (*) if you want to select all columns and insert them as they are.
Since you are changing the PRIMARY KEY, you need to enumerate.
However, you can create a before update trigger and change the value of the PRIMARY KEY in this trigger.
Note that the trigger cannot reference the table itself, so you will need to provide some other way to get the unique number (like a sequence):
CREATE TRIGGER trg_mytable_bi BEFORE INSERT ON mytable FOR EACH ROW
BEGIN
:NEW.id := s_mytable.nextval;
END;
This way you can use the asterisk but it will always replace the value of the PRIMARY KEY.

Resources