0
我需要在SQLite中存儲一棵樹。我發現了一個很不錯的方法,用於SQL Server的位置:查詢從SQL Server到SQLite的轉換
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構建此觸發器功能?
謝謝,我明白了。任何想法如何獲得與SQL Server相同的結果? – metamagicson