简体   繁体   中英

PL-SQL manipulate column and insert

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?

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%';

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM