我正在尝试编写一个递归过程,该过程将删除节点及其所有子节点(如果它们在表中).我尝试执行以下操作
I am trying to write a recursive procedure that would delete the node and all it's children if they are such in the table. I tried doing the following
CREATE PROCEDURE DeleteFile
@FileID INTEGER,
@UserID VARCHAR(MAX)
AS
DELETE FROM [FileTree] WHERE [ID] = @FileID AND [UserID]=@UserID;
IF EXISTS(SELECT * FROM [FileTree] WHERE [ParentID] = @FileID AND [UserID]=@UserID)
BEGIN
DECLARE FileCursor CURSOR LOCAL FOR
SELECT [ID],[UserID] FROM [FileTree] WHERE [ParentID] = @FileID AND [UserID]=@UserID;
OPEN FileCursor
FETCH NEXT FROM FileCursor INTO @FileID , @UserID
WHILE @@FETCH_STATUS =0
BEGIN
EXEC DeleteFile @FileID,@UserID;
FETCH NEXT FROM FileCursor INTO @FileID , @UserID ;
END
END
ELSE
return
但由于某种原因,这不起作用.它删除了节点,但孩子们仍然存在.表,,设计".
But for some reason this is not working. It deletes the node but the kids remain. Table ,,design" .
CREATE TABLE [FileTree] (
[ID] INT IDENTITY NOT NULL,
[Name] VARCHAR (MAX) NOT NULL,
[ParentID] INT NULL,
[UserID] VARCHAR (MAX) NOT NULL
);
你能指出我犯的错误并建议一个工作程序吗?UPD:我将游标设为 LOCAL 并且在进入 while 循环之前我正在获取一次,但它仍然没有删除所有的孩子.
Can you please indicate the errors I made and suggest a working procedure ? UPD: I made the cursor LOCAL and I am fetching one time before going into the while loop, it still does not delete all the children.
我认为你有语法问题.我是这样修复的
I think you have syntax problem.i fixed it like this
CREATE PROCEDURE DeleteFile
@FileID INTEGER,
@UserID VARCHAR(MAX)
AS
BEGAIN
DELETE FROM [FileTree] WHERE [ID] = @FileID AND [UserID]=@UserID;
IF EXISTS(SELECT * FROM [FileTree] WHERE [ParentID] = @FileID AND [UserID]=@UserID)
BEGIN
DECLARE FileCursor CURSOR LOCAL FOR
SELECT [ID],[UserID] FROM [FileTree] WHERE [ParentID] = @FileID AND [UserID]=@UserID;
OPEN FileCursor
FETCH NEXT FROM FileCursor INTO @FileID , @UserID
WHILE @@FETCH_STATUS =0
BEGIN
EXEC DeleteFile @FileID,@UserID;
FETCH NEXT FROM FileCursor INTO @FileID , @UserID ;
END
END
END
这篇关于删除 SQL 表中的树节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
将每个子标记转换为具有多个分隔符的单列-SQLConverting Every Child Tags in to a Single Column with multiple Delimiters -SQL Server (3)(将每个子标记转换为具有多个分隔符的单列-SQ
如何从多个表创建视图?How can I create a view from more than one table?(如何从多个表创建视图?)
根据前一行内的计算值创建计算值Create calculated value based on calculated value inside previous row(根据前一行内的计算值创建计算值)
如何将表格的前两列堆叠成一列,但也仅将第三How do I stack the first two columns of a table into a single column, but also pair third column with the first column only?(如何将表格的前两列堆
递归 t-sql 查询Recursive t-sql query(递归 t-sql 查询)
将月份名称转换为日期/月份编号(问题和答案的组Convert Month Name to Date / Month Number (Combinations of Questions amp; Answers)(将月份名称转换为日期/月份编号(问题和答案的组合