【问题标题】:incompatible SQL trigger不兼容的 SQL 触发器
【发布时间】:2011-04-04 10:29:31
【问题描述】:

作为 SQL 新手,能否帮助我将此触发器调整为 sqlite 或 HSQLDB,或者建议不同的方法?

我的数据库中有这张表:

CREATE TABLE IF NOT EXISTS dfTree 
(
id INTEGER, 
parentId INTEGER,
name VARCHAR(20),
depth INTEGER,
lineage VARCHAR(100)
)

我尝试设置触发器,但它似乎与我尝试过的两个数据库(sqlite 和 HSQLDB)都不兼容

CREATE TRIGGER dfTree_InsertTrigger ON dfTree
FOR INSERT AS
UPDATE child
    -- set the depth of this "child" to be the
    -- depth of the parent, plus one.
    SET depth = ISNULL(parent.depth + 1,0),
    -- the lineage is simply the lineage of the parent,
    -- plus the child's ID (and appropriate '/' characters
    lineage = ISNULL(parent.lineage,'/') + LTrim(Str(child.id)) + '/'
-- we can't update the "inserted" table directly,
-- so we find the corresponding child in the
-- "real" table
FROM dfTree child INNER JOIN inserted i ON i.id=child.id
-- now, we attempt to find the parent of this
-- "child" - but it might not exist, so these
-- values may well be NULL
LEFT OUTER JOIN dfTree parent ON child.parentId=parent.id

(触发器应该在新条目时计算“深度”和“血统”字段。我正在关注http://www.developerfusion.com/article/4633/tree-structures-in-aspnet-and-sql-server/2/上关于树结构的文章

再次,作为 SQL 的新手,能否帮助我将此触发器调整为 sqlite 或 HSQLDB,或者建议一种不同的方法?

谢谢!

【问题讨论】:

    标签: sql sqlite hsqldb


    【解决方案1】:

    这应该可行:

    CREATE TRIGGER dfTree_InsertTrigger 
    after insert ON dfTree 
    for each row
    begin
      UPDATE dftree SET   
        depth = (select coalesce(depth + 1, 1) from (select depth from dftree parent where parent.id = new.parentid union all select null depth)),
        lineage = (select coalesce(lineage,'/') || dftree.id || '/' from (select lineage from dftree parent where parent.id = new.parentid union all select null lineage))
      where new.id = id;
    end;
    

    几点说明:
    - SQL 中字符串连接的运算符是 ||,而不是 +
    - coalesce() 应该比 isnull 更便携
    - union all .. 部分确保我们总是得到一行(即使不存在父级)

    【讨论】:

    • 工作就像一个魅力!非常感谢!
    猜你喜欢
    • 2011-09-30
    • 1970-01-01
    • 2018-07-27
    • 2016-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多