不兼容的SQL触发器

时间:2011-04-04 10:29:31

标签: sql sqlite hsqldb

作为SQL的新手,有些人可以帮助我将这个触发器调整为sqlite或HSQLDB,或者建议采用不同的方法吗?

我在db中有这个表:

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

我尝试设置一个触发器,但它似乎与我尝试的db(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,或者可能建议采用不同的方法吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

这应该有效:

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 .. part确保我们总是得到一行(即使没有父级)