2014-10-16 110 views
2

我在我的數據庫(Oracle 11g)中有一個很大的表,我想更新表中有特定數字的一列。 我想通過設置此列的每個值的前面的prefix來更新它。Oracle:通過添加到現有值來更新數據行

(SpecificNumber是int和PK,值1是Varchar2,所以是最後一列):

實際數據:

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

未來的數據(我的SQL後):

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

所以我想到了:

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

但是,這給我一個ORA-00904: "p": invalid identifier錯誤。

如果我試試這個:

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

我得到一個ORA-01722: invalid number錯誤。

這甚至可能嗎?已經感謝您的幫助!

+0

'SET column2gettingupdated = CONCAT( 「前綴 - 」,column2gettingupdated)' – Mihai 2014-10-16 13:38:10

+0

@Mihai真。不知何故忘了CONCAT,並一直認爲它只適用於MySQL。無論如何,它發佈作爲答案,你得到的信貸! (但是,如果你使用「替換」,你會得到無效的標識符錯誤。) – DatRid 2014-10-16 13:45:02

回答

5

所有這一切需要的是使用連接運算符,||。更新語法並不要求您有一個子查詢才能獲得值爲的column2gettingupdated

另外,對於Oracle VARCHAR2,您使用單引號而不使用雙引號。這導致了這個語法對於這一說法:

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

以下是示例模式SCOTT一個例子:

[email protected]> CREATE TABLE DEPT2 as (
    2   SELECT * 
    3   FROM DEPT 
    4  ); 

Table created. 

[email protected]> commit; 

Commit complete. 

[email protected]> UPDATE DEPT2 
    2  SET DNAME = 'PRE '|| DNAME 
    3 WHERE DEPTNO = 20; 

1 row updated. 

[email protected]> commit; 

Commit complete. 

[email protected]> SELECT * 
    2 FROM dept 
    3 WHERE deptno = 20 
    4 UNION 
    5 SELECT * 
    6 FROM dept2 
    7 WHERE deptno = 20 
    8 
[email protected]>/

    DEPTNO DNAME   LOC 
========== ============== ============= 
     20 PRE RESEARCH DALLAS 
     20 RESEARCH  DALLAS 
2

字符串使用串聯:

update <table_name> 
    set column2gettingupdated = 'Prefix-' || column2gettingupdated 
where specificnumber = 12233; -- use NUMBER literal instead of string one 
相關問題