存储过程 高手请进

hebeiman 2004-04-21 06:37:02
id Parent_id name
1 0 sdf
2 1 sdf
3 1 sdf
4 2 sdf
5 2 sdf
6 3 asdf
7 3 asdf

有意上表
假如删除1的话 那么必须删除 parent_id 是1的 那么就会删除 2,3 。 2,3删除了及必须删除 parent_id 是 2,3 的 以此类推
请高手写出 存储过程
输入参数 为 编号 id
...全文
77 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
qizhanfeng 2004-04-22
  • 打赏
  • 举报
回复
学习
zjcxc 2004-04-22
  • 打赏
  • 举报
回复
create proc p_delete
@id int --要删除的id
as
create table #t(id int,level int)
declare @l int
set @l=0
insert #t select @id,@l
while @@rowcount>0
begin
set @l=@l+1
insert #t select a.id,@l
from 表 a join #t b on a.Parent_id=b.id
where b.level=@l-1
end
delete a
from 表 a join #t b on a.id=b.id
go

--调用
exec p_delete 2
pbsql 2004-04-22
  • 打赏
  • 举报
回复
用触发器:
CREATE TRIGGER tr_delete ON dbo.t1
FOR DELETE
AS
delete from t1 where Parent_id in (select id from deleted)
Functions 2004-04-22
  • 打赏
  • 举报
回复
首先删除pid = 1
然后使用循环删除,PID不在ID里面的(PID=0的除外),行不行?
delete t1

insert into t1
select 1, 0, 'sdf'
union
select 2, 1, 'sdf'
union
select 3, 1, 'sdf'
union
select 4, 2, 'sdf'
union
select 5, 2, 'sdf'
union
select 6, 3, 'asdf'
union
select 7, 3, 'asdf'
go

select * from t1
go

delete from t1 where pid = 1
while @@rowcount>0
delete from t1 where pid not in (select id from t1 ) and pid <> 0
hebeiman 2004-04-22
  • 打赏
  • 举报
回复
咋没人恢复呀 我顶

22,297

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧