2011-04-04 62 views
0

作爲SQL中的新手,有人可以幫助我將此觸發器調整爲sqlite或HSQLDB,或者可能會提出一種不同的方法?不兼容的SQL觸發器

我這個表我的數據庫:

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中的新手,可以幫助我ada這觸發器要麼SQLite或HSQLDB,或者可能建議一種不同的方法?

謝謝!

回答

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
更便攜 - 工會所有..部分確保我們總能得到一排(即使沒有父母存在)

+0

工作就像一個魅力!非常感謝你! – user653952 2011-04-05 10:44:27