日期:2014-05-18  浏览次数:20410 次

请问这个情况如何实现?
本来这个是应该发到SQL版块的,但那人气很少就发这里了。

MS   SQL中一个表,有两个项   :   ID   和ParentID   都是int
ParentID   =   0表示主记录
ParnetID   =   n(n!=0)表示子记录
其中n定是另一个记录(可能为子记录)的ID值

如:
ID           ParentID
1                   0
2                   0
3                   1
4                   3
5                   4
6                   1
7                   6
8                   7

现在我想实现删一条记录时的同时,让数据库自动把这条记录的
子记录也删掉。
如删ID=1时同时也删掉345678
删ID=6时,也删7和8

如何实现,我想用Trgger,但为什么只能触发一层呢?
数据库菜鸟。

请高手帮忙!


------解决方案--------------------
在数据库里写个函数,用递归
------解决方案--------------------
http://www.google.cn/search?q=%22sql+server%22+%E8%A7%A6%E5%8F%91%E5%99%A8+%E7%9B%B4%E6%8E%A5%E9%80%92%E5%BD%92&sourceid=ie7&rls=com.microsoft:en-US&ie=utf8&oe=utf8
------解决方案--------------------
create proc DeleteID(@ID int)
AS
declare @sid bit
set @sid = 1
while @sid <> 0
begin
if (Exists(Select ID from [mytable] where ParentID=@ID))
begin
delete from [mytable] where ID=@ID
select @ID=ID from [mytable] Where ParentID=@ID
end
else
begin
delete from [mytable] where ID=@ID
set @sid = 0
end
end