2009-08-05 81 views
0

我有兩個表具有以下字段:更新表的多個列

表1:OTNAME 表2:SNCODE,描述文本

我想表2的兩列添加到表1和更新列。我的查詢是:

alter table table1 add sncode integer        
alter table table1 add description_text varchar2(30) 

update table1 set 
sncode,description_text = (SELECT sncode, description_text 
    FROM table2, table1 
    WHERE SUBSTR (otname, INSTR (otname,'.', 1, 3) 
         + 1, 
         INSTR (otname, '.', 1, 4) 
           - INSTR (otname,'.', 1, 3) 
           - 1) 
           = sncode) 

我得到一個錯誤:ORA 00927-缺少等於操作符,指向我的更新語句的第二行。感謝有人能指引我走向正確的方向。

問候,

新手

回答

4
MERGE 
INTO table1 t1 
USING table2 t2 
ON  (SUBSTR (otname, INSTR (otname,'.', 1, 3) 
         + 1, 
         INSTR (otname, '.', 1, 4) 
           - INSTR (otname,'.', 1, 3) 
           - 1) 
           = t2.sncode)) 
WHEN MATCHED THEN 
UPDATE 
SET t1.sncode = t2.sncode, 
     t1.description_text = t2.description_text 

您也可以簡化您的表情:

MERGE 
INTO table1 t1 
USING table2 t2 
ON  (REGEXP_SUBSTR(otname, '[^.]+', 1, 4) = t2.sncode) 
WHEN MATCHED THEN 
UPDATE 
SET t1.sncode = t2.sncode, 
     t1.description_text = t2.description_text 
0

嘗試更新設置爲從結構代替。 喜歡的東西

update table1 
set sncode = t1.sncode, description_text = t1.description_text 
from table2 as t2, table1 as t1 
where SUBSTR (otname, INSTR (otname,'.', 1, 3) 
        + 1, 
        INSTR (otname, '.', 1, 4) 
          - INSTR (otname,'.', 1, 3) 
          - 1) 
          = sncode) 
+0

不,這是關於甲骨文。這個問題沒有明確提到,但它是用oracle和oracle10g標記的。 – nagul 2009-08-05 10:25:22

+0

我正在使用Oracle 10g。我得到一個錯誤:「SQL命令沒有正確結束」 – novice 2009-08-05 10:26:36

+0

sncode之後似乎有一個額外的paranthesis?運行該命令作爲`select t1.sncode,t1.description_text from table2..`來首先了解什麼是錯誤的。進一步細分where子句,最終你會發現錯誤的位。即嘗試`從table2`選擇substr(...)等等。 – nagul 2009-08-05 11:19:51

1

你的問題是你缺少圍繞着田野支架進行更新。嘗試

update table1 set 
(sncode,description_text) = (SELECT sncode, description_text 
    FROM table2, table1 
    WHERE SUBSTR (otname, INSTR (otname,'.', 1, 3) 
         + 1, 
         INSTR (otname, '.', 1, 4) 
           - INSTR (otname,'.', 1, 3) 
           - 1) 
           = sncode) 
0

我懷疑你不應該包括在SELECT查詢table1。也許這個聲明將起作用:

UPDATE table1 
    SET 
     (sncode, description_text) 
     = 
     (
     SELECT table2.sncode, table2.description_text 
      FROM table2 
      WHERE SUBSTR(
        table1.otname, 
        INSTR(table1.otname,'.', 1, 3) + 1, 
        INSTR(table1.otname, '.', 1, 4) - INSTR (table1.otname,'.', 1, 3) - 1 
       ) = table2.sncode 
     )