2017-07-25 60 views
1

我開始使用sql,並且我面對分層查詢。同時我成功選擇connect by prior命令行但未能更新。這裏是我的更新查詢:更新查詢的SQL語法與之前的連接

update HTABLE set status = 'INACTIVE' 
    WHERE STATUS <> 'CLOSE' 
    Connect by prior PARENT_ID=ID start with PARENT_ID=12345; 

SQL Error: ORA-00933: SQL command not properly ended和會很高興知道如何使用分層更新表..

謝謝!

編輯 我也試圖把where條件在start with,而不是幫助:

update HTABLE set status = 'INACTIVE' 
    Connect by prior PARENT_ID=ID start with PARENT_ID=12345 AND STATUS <> 'CLOSE'; 

回答

2

分層查詢只適用於SELECT。它不適用於更新(我同意它可以是整潔的,如果它)。

那麼你可以做的是這樣的:

update HTABLE 
set status = 'INACTIVE' 
WHERE STATUS <> 'CLOSE' 
and id in (select c.id 
      from htable 
      connect by prior ID = PARENT_ID 
      start with PARENT_ID = 12345); 

注列connect by prior ID = PARENT_ID的順序。通常我們想從START WITH行走到樹上,這就是我所做的。您的訂購connect by prior PARENT_ID = ID從12345行走到它的父母,祖父母等樹。如果這是你想要的,切換connect by條款。

1

,您可以更新使用條款where id in (select ... connect by...)或者您可以使用merge

merge into htable h 
using (select distinct id 
     from htable 
     where status <> 'CLOSE' 
     connect by prior parent_id = id 
     start with parent_id = 11) src 
on (h.id = src.id) 
when matched then update set status = 'INACTIVE' 

測試數據:

create table htable (id number(4), parent_id number(4), status varchar2(10)); 
insert into htable values ( 1, null, 'ACTIVE'); 
insert into htable values ( 11, 1, 'CLOSE'); 
insert into htable values ( 12, 1, 'ACTIVE'); 
insert into htable values (111, 11, 'ACTIVE'); 
insert into htable values (112, 11, 'ACTIVE'); 
insert into htable values (121, 12, 'ACTIVE'); 
insert into htable values ( 2, null, 'ACTIVE'); 
insert into htable values ( 21, 2, 'ACTIVE'); 
insert into htable values (211, 21, 'ACTIVE'); 
insert into htable values (212, 21, 'ACTIVE'); 

merge

ID PARENT_ID STATUS 
----- --------- ---------- 
    1   INACTIVE 
    11   1 INACTIVE 
    12   1 ACTIVE 
    111  11 INACTIVE 
    112  11 INACTIVE 
    121  12 ACTIVE 
    2   ACTIVE 
    21   2 ACTIVE 
    211  21 ACTIVE 
    212  21 ACTIVE