Search code examples
sqlplsqlsubstrreplicate

PLSQL - How to replicate a row changing columns first characters?


I have a table with products like this:

PRODUCT_ID    SUB_PRODUCT_ID    DESCRIPTION   CLASS
----------    --------------    -----------   -----
A001        ACC1                coffeemaker   A
A002        ACC1                toaster       A
A003        ACC2                coffee table  A
A004        ACC5                couch         A

I need to replicate a row changing only first characters in some columns to get a result like this in the same table, for example if I take the first row I want to copy PRODUCT_ID changing only the first letter (from A001 to B001), SUB_PRODUCT_ID changing only the first letter (from ACC1 to BCC1), keep DESCRIPTION and change CLASS (from A to B)

PRODUCT_ID    SUB_PRODUCT_ID    DESCRIPTION   CLASS
----------    --------------    -----------   -----
A001          ACC1              coffeemaker   A
B001          BCC1              coffeemaker   B

I have been trying using SUBSTR function without positive results.


Solution

  • is this what you want?

    insert into products(PRODUCT_ID, SUB_PRODUCT_ID, DESCRIPTION, CLASS)
        select replace(product_id, 'A', 'B'),
               replace(SUB_PRODUCT_ID, 'A', 'B'),
               DESCRIPTION,
               replace(CLASS, 'A', 'B')
        from products
        where class = 'A';
    

    EDIT:

    replace() might be overkill:

    insert into products(PRODUCT_ID, SUB_PRODUCT_ID, DESCRIPTION, CLASS)
        select 'B' || substr(product_id, 2),
               'B' || substr(SUB_PRODUCT_ID, 2),
               DESCRIPTION,
               'B'
        from products
        where class = 'A';