我有这样的文件夹结构:
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