Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query to assign the same ID to row being inserted if it it already exists in the table

Tags:

sql

oracle

plsql

I am inserting customer records into a table where, if a record with the same name already exists, I assign the same ID to the newly inserted record.

Assume table T has this record:

ID | Name | Phone_Number | Date_Inserted
105| Sam  | 111111       | 04/03/2014
106| Rita | 222222       |04/03/2014

And I'm inserting this from table A:

Name| Phone_Number
Sam | 333333

Then after insertion, table T should have:

ID | Name | Phone_Number | Date_Inserted
105| Sam  | 111111       | 04/03/2014
106| Rita | 222222       | 04/03/2014
105| Sam  | 333333       | 04/04/2014

Without the above change it would look like:

INSERT INTO T SELECT CustID.nextval,Name,Phone_Number,SYSDATE FROM A;

I was thinking of using,

INSERT INTO T
  SELECT CASE 
           WHEN NOT EXISTS(select null from T WHERE T.Name=A.Name) THEN CustID.nextVal
           ELSE (select ID from T where T.Name=A.Name) 
         END, 
         Name,
         Phone_Number,
         SYSDATE 
   FROM A;

But I'm not sure if it'll work and it seems redundant/bad for performance. If there's a preferred way to do this, please let me know.

like image 600
user3808188 Avatar asked Jul 31 '14 17:07

user3808188


People also ask

How do you check if record already exists in SQL?

The EXISTS operator is used to test for the existence of any record in a subquery. The EXISTS operator returns TRUE if the subquery returns one or more records.

How do you find out if a record already exists in a database if it doesn't insert a new record Oracle?

EXISTS executes the query we tell it to (the SELECT ) and returns a boolean value. If it finds the record, we return 'This record already exists!' to our recordset and do nothing else. If it doesn't exist, we execute our INSERT statement, and then return 'Record Added' to our recordset.

What should be done if you need to insert a row before or after existing row?

To store a row before all other rows, insert the new row with a rowid value that is smaller than all others: INSERT INTO MyTable(rowid, Name, Comment) VALUES ((SELECT MIN(rowid) FROM MyTable) - 1, 'me', 'first!


1 Answers

If your schema is not set in stone, I would perhaps reconfigure it so that there is a "person" table and a separate "person phone number" table. With that sort of set up, you can associate multiple phone numbers with one person, and you won't be stomping on IDs, or creating confusing secondary ID columns that aren't primary keys.

like image 99
Jeff N Avatar answered Nov 08 '22 23:11

Jeff N