用于通过先前连接的更新查询的sql语法

时间:2017-07-25 07:24:18

标签: oracle hierarchical-query

我开始使用sql,我遇到了分层查询。同时我成功用connect by prior命令选择行但无法更新。这是我的更新查询:

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 个答案:

答案 0 :(得分:4)

分层查询仅适用于SELECT。它不适用于UPDATE(我同意它可能是整洁的,如果它)。

所以你能做的就是:

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 :(得分: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
相关问题