`

sql删除树节点 及其子节点的全部(存储过程,游标,递归)

阅读更多

删除父节点及父节点之下的全部节点

比如删除节点为3,将递归删除其下的全部节点6,11,12

 表里面需要创建ID ,PID TID用处以后对树的复制操作 表格式如图所示:

PID用于存放节点的值 name存放内容 ID自动增长

0节点存在ID为1的节点 1节点下存在ID为2,3的节点 依次类推....

alter procedure DelereNote
 @id int--定义要删除树节点
 as
declare @childID int--声明变量
 declare cursors cursor local for select id from test where pid=@id--local关键字 全局游标
 open cursors
  fetch next from cursors into @childID--取游标的值赋给变量
  while(@@FETCH_STATUS=0)--判断当前游标内是否存在值
  begin
    exec DelereNote @childID--递归调用存储过程 把孩子节点的值赋给游标 递归调用
    fetch next from cursors into @childID--继续读取游标里面的内容
  end  
  close cursors
  deallocate cursors
delete from test where ID=@id--存储过程执行的删除方法
 
exec DelereNote 6--调用储存过程对于递归调用不很容易理解 需要多加练习

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics