Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle: Update a datarow by adding to existing value

I have a big table in my database(Oracle 11g) where I want to update a column of the table where I have specific numbers in it. I want to update it with setting a prefix infront of every value of this column.

Example (SpecificNumber is int and the PK, Value1 is Varchar2 and so is the last column):

Actual data:

    [SpecificNumber] [Value1] [column2gettingupdated]
[1]  123456789        Test     text    
[2]  123456789102     sth      text2    
[3]  12233            text     test3

Future data(after my sql):

    [SpecificNumber] [Value1] [column2gettingupdated]
[1]  123456789        Test     PREFIX-text    
[2]  123456789102     sth      PREFIX-text2    
[3]  12233            text     PREFIX-test3

So what I thought about:

Update table
set column2gettingupdated=("prefix"+
    (select column2gettingupdated from table where SpecificNumber = '12233')
)
where SpecificNumber = '12233';

But that gives me an ORA-00904: "p": invalid identifier error.

And if I try this:

Update table
set column2gettingupdated=("prefix"+
    (select column2gettingupdated from table where SpecificNumber = '12233')
)
where SpecificNumber = '12233';

I get an ORA-01722: invalid number error.

Is this even possible ? Already thanks for your help!

like image 683
DatRid Avatar asked Oct 16 '14 13:10

DatRid


2 Answers

Use concatenation for strings:

update <table_name>
   set column2gettingupdated = 'Prefix-' || column2gettingupdated 
 where specificnumber = 12233; -- use NUMBER literal instead of string one
like image 124
Rusty Avatar answered Nov 16 '22 02:11

Rusty


All that is needed is to use the concatenation operator, ||. Update syntax does not require that you have a subquery to obtain column2gettingupdated for the value, 12233.

Also, with Oracle VARCHAR2's, you use single quotes and not double quotes. This results in this syntax for this statement:

UPDATE table
   SET column2gettingupdated = 'prefix' || column2gettingupdated
 WHERE SpecificNumber        = 12233;

Here is an example from the example schema SCOTT:

SCOTT@dev> CREATE TABLE DEPT2 as (
  2          SELECT *
  3            FROM DEPT
  4         );

Table created.

SCOTT@dev> commit;

Commit complete.

SCOTT@dev> UPDATE DEPT2
  2     SET DNAME  = 'PRE '|| DNAME
  3   WHERE DEPTNO = 20;

1 row updated.

SCOTT@dev> commit;

Commit complete.

SCOTT@dev> SELECT *
  2    FROM dept
  3   WHERE deptno = 20
  4   UNION
  5  SELECT *
  6    FROM dept2
  7   WHERE deptno = 20
  8  
SCOTT@dev> /

    DEPTNO DNAME          LOC
========== ============== =============
        20 PRE RESEARCH   DALLAS
        20 RESEARCH       DALLAS
like image 29
Patrick Bacon Avatar answered Nov 16 '22 01:11

Patrick Bacon