DatRid DatRid - 5 months ago 12
SQL Question

Update a datarow by adding characters 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
Varchar
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!

Btw, if you have a better title for the question - just go on. I didn't know how to describe it in little words.

Answer

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