以递归方式从表中删除记录 - SQL Server 2008

时间:2010-08-12 10:29:39

标签: .net sql sql-server

表格结构

ID       DESC             PARENT_ID**

35151    Parent            35154
35152    System            35151
35153    Same as System    35151
35154    ParentsParent     35157
35156    Product           35157
35157    Login Group       35159

其中

Id是主键,parent_id是同一表中引用的外键

如何递归删除记录,从最后一个子项开始直到父项。如果没有子记录,则应删除父记录。如果发生奇怪的事情,我需要使用事务回滚。

2 个答案:

答案 0 :(得分:5)

您可以使用递归CTE来删除列表。

https://data.stackexchange.com/stackoverflow/query/9287/so3466713

-- SO3466713

CREATE TABLE #t (
    ID int NOT NULL
    ,[DESC] varchar(50) NOT NULL
    ,PARENT_ID int NULL
)

INSERT INTO #t VALUES
(35151, 'Parent', 35154)
,(35152, 'System', 35151)
,(35153, 'Same as System', 35151)
,(35154, 'ParentsParent', 35157)
,(35156, 'Product', 35157)
,(35157, 'Login Group', 35159)

;WITH tree AS (
    SELECT *
    FROM #t
    WHERE [DESC] = 'Parent'

    UNION ALL

    SELECT c.*
    FROM #t AS c
    INNER JOIN tree AS p
        ON c.PARENT_ID = p.ID
)
-- SELECT *
-- FROM tree
DELETE FROM #t WHERE ID IN (SELECT ID FROM tree)

SELECT * FROM #t​

答案 1 :(得分:1)

看看这个问题:

SQL Server: Self-reference FK, trigger instead of ON DELETE CASCADE

使用ON DELETE CASCADE的FK在SQL Express 2005中不起作用,可能会在2008年运行

ALTER TABLE SomeChildTable 
CONSTRAINT YOurConstraintName 
FOREIGN KEY (YourParentId)
REFERENCES YourParentTable(ParentTableId) ON DELETE CASCADE;