插入时分层生成的树代码

Hierarchical generated tree code on insert

http://i.stack.imgur.com/weX9W.jpg

在我的 table 中的每个插入中,我想根据我正在插入的对象的父级代码生成此代码(1、1.1、1.2 ...)。

我的方法是这样的: - 制作一些 SQL 函数,以某种方式生成此代码,并且在我的 table.

中的每次插入时都会通过触发器调用她

在字符串解析方面遇到了一些困难,那么您认为最好的解决方案是什么?谢谢

你可以只找到父对象,假设它的代码是 1.3,然后计算具有相同父对象的兄弟行,假设你找到了 2 个兄弟。 所以你的新代码值为 1.3.3。但是此方法需要从您的触发器工作的相同 table 中进行选择。 当您一次插入多行时,这可能会导致 "ORA-04091: table name is mutating, trigger/function may not see it"。 有workarounds可以避免这种情况。

另一种方法是使用基于此查询的视图,而不是触发器:

select id, pid, ltrim(sys_connect_by_path(rn, '.'),'.') code
  from (
    select id, pid, 
           row_number() over (partition by level, pid order by seq) rn
      from data connect by pid = prior id
      start with pid is null )
  connect by pid = prior id
  start with pid is null

SQLFiddle demo

它要求您的 table 包含列 seq 以允许对行进行正确排序。