1

我有这样的文件夹结构:

Folder1
  Folder1.1
  Folder1.2
Folder2
  Folder2.1
    Folder2.1.1
and so on..

问题是如何级联删除它们(即,当删除文件夹 2 时,所有子项也被删除)。我无法设置 ON DELETE 操作,因为 MSSQL 不允许这样做。你能给一些建议吗?

更新:我写了这个存储过程,我可以留下它还是需要一些修改?

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE sp_DeleteFoldersRecursive
    @parent_folder_id int
AS
BEGIN
    SET NOCOUNT ON;

    IF @parent_folder_id = 0 RETURN;

    CREATE TABLE #temp(fid INT );

    DECLARE @Count INT;

    INSERT INTO #temp(fid)
    SELECT FolderId FROM Folders WHERE FolderId = @parent_folder_id;

    SET @Count = @@ROWCOUNT;

    WHILE @Count > 0
    BEGIN
        INSERT INTO #temp(fid) 
            SELECT FolderId FROM Folders WHERE EXISTS
                   (SELECT FolderId  FROM #temp
                    WHERE Folders.ParentId = #temp.fid)
             AND  NOT EXISTS
                  (SELECT FolderId FROM #temp
                   WHERE Folders.FolderId = #temp.fid);    

             SET @Count = @@ROWCOUNT;         
    END

    DELETE Folders FROM Folders INNER JOIN #temp ON Folders.FolderId = #temp.fid; 
    DROP TABLE #temp;
END
GO
4

1 回答 1

0

通常它是一个存储过程或 INSTEAD OF 触发器。

那是:

  • 从参数/DELETED(例如递归 CTE 方法)生成 Folder2 的层次结构)
  • 在一个 DELETE 语句中删除此层次结构

循环级联/外键违规不会触发。

于 2011-01-30T19:34:18.027 回答