我需要在SQLite中存储一棵树。我在这里找到了一个非常好的SQL Server方法:
Tree structures in ASP.NET and SQL Server
触发器的概念是明确的最终前瞻性思维。
我尝试将描述的触发器翻译成SQLite
SQL Server版本:
CREATE TRIGGER dfTree_UpdateTrigger
ON dfTree
FOR UPDATE AS
-- if we've modified the parentId, then we
-- need to do some calculations
IF UPDATE (parentId)
UPDATE child
-- to calculate the correct depth of a node, remember that
-- - old.depth is the depth of its old parent
-- - child.depth is the original depth of the node
-- we're looking at before a parent node moved.
-- note that this is not necessarily old.depth + 1,
-- as we are looking at all depths below the modified
-- node
-- the depth of the node relative to the old parent is
-- (child.depth - old.depth), then we simply add this to the
-- depth of the new parent, plus one.
SET depth = child.depth - old.depth + ISNULL(parent.depth + 1,0),
lineage = ISNULL(parent.lineage,'/') + LTrim(Str(old.id)) + '/' +
right(child.lineage, len(child.lineage) - len(old.lineage))
-- if the parentId has been changed for some row
-- in the "inserted" table, we need to update the
-- fields in all children of that node, and the
-- node itself
FROM dfTree child
INNER JOIN inserted old ON child.lineage LIKE old.lineage + '%'
-- as with the insert trigger, attempt to find the parent
-- of the updated row
LEFT OUTER JOIN dfTree parent ON old.parentId=parent.id
我的SQLite版本到现在为止:
CREATE TRIGGER IF NOT EXISTS sc_compare_UpdateTrigger
AFTER UPDATE ON dfTree
FOR EACH ROW
BEGIN
UPDATE child
SET depth = child.depth - OLD.depth + IFNULL(parent.depth + 1,0),
lineage = IFNULL(parent.lineage,'/') + LTrim(CAST(OLD.id AS TEXT)) + '/' +
right(child.lineage, len(child.lineage) - len(OLD.lineage))
FROM dfTree child
INNER JOIN inserted OLD ON child.lineage LIKE OLD.lineage + '%'
LEFT OUTER JOIN dfTree parent ON OLD.parentId=parent.id
END;
对于此版本,"错误:接近" FROM":语法错误" occours。
我走在正确的轨道上? 是否可以使用SQLite构建此触发器功能?
答案 0 :(得分:0)
Sqlite UPDATE语法不支持FROM子句。
另请注意,insetred
触发器中没有NEW
表,OLD
,FOR EACH ROW
行。