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.
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.
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.
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With