Reputation: 359
I added new column to my existing table, my aim to insert data to the new column with using existing column's data after some manipulation, such as adding prefix. the new and existing column's type is string. How can I perform it ? I have no idea about plsql. SQL is enough for this situation?
Upvotes: 2
Views: 222
Reputation: 6745
Just update all records in a table.
It's possible to do it in single run through all records:
update existing_table
set
newcolumn = case
when (length(oldcolumn) = 13) and (oldcolumn like '+%')
then oldcolumn
when (length(oldcolumn) = 12) and (oldcolumn like '90%')
then '+' || oldcolumn
when (length(oldcolumn) = 10) and not (oldcolumn like '+%')
then '+90' || oldcolumn
else '?'
end
After update it's possible to check for invalid conversions:
select oldcolumn, newcolumn
from existing_table
where newcolumn = '?'
and correct case
conditions or update remaining records one by one.
Upvotes: 1
Reputation: 3565
I haven't got PL/SQL here, so I can't test it but it should be easy.
Let's start by altering the table:
ALTER TABLE table_name
ADD new_column varchar2(50);
Then, let's update it.
We'll start by adding all the values from the old_column that don't begin with the prefix.
UPDATE table_name t1
SET t1.new_column = 'prefix' || t1.old_column
WHERE t1.old_column NOT LIKE 'prefix%';
Then, we can simply copy the values from the old_column that already have the prefix
UPDATE table_name t1
SET t1.new_column = t1.old_column
WHERE t1.old_column LIKE 'prefix%';
Upvotes: 3