有个表就比如表名为USE吧,有三列:ID,Name,ParentID,给出一个ID,删除该行,然后根据该行的ParentID,找出表中ID=ParentID的行删除,在根据删除的第二行的ParentID找出相应的ID行删除,依次进行删除,请问用SQL语句怎么写?后者其它方法不用SQL语句也行,请高手帮忙。SQLSERVER
此类问题,纯属表结构设计有问题,看这儿:
http://www.cnblogs.com/downmoon/archive/2009/10/23/1588405.html
解决方法不是没有,比较费劲:
IF NOT OBJECT_ID('[Use]') IS NULL
DROP TABLE [Use]
GO
Create table [Use]
(
ID int primary key identity(1,1)
,[Name] nvarchar(50) null
,ParentID int null
)
go
insert into [Use]
select '名称', 0
union all
select '名称2', 1
union all
select '名称3', 1
union all
select '名称4', 2
union all
select '名称5', 4
union all
select '名称6', 4
select * from [Use]
/********
ID Name ParentID
1 名称 0
2 名称2 1
3 名称3 1
4 名称4 2
5 名称5 4
6 名称6 4
********/
Create proc CCP_DeleparentIDByPKID
(@DelID int ----传入参数
)
as
/*递归删除,假定ParentID=0为根,即不再有父ID*********************************/
Declare @LevelCount int --递归的最大层次
Declare @tmpID int
Declare @tmpParentID int
set @tmpParentID=(select ParentID from [Use] where ID=@DelID)
if(@tmpParentID>0)
Begin
delete from [use] where ID=@DelID
while(@tmpParentID>0)
Begin
set @tmpID=(select ParentID from [use] where ID=@tmpParentID)
delete from [use] where ID=@tmpParentID
set @tmpParentID=@tmpID
set @LevelCount=@LevelCount 1
if(@LevelCount>5)--最多五层,防止死循环
Break
END
End
ELSE
BEGIN
--没有父ID,只删除当前行即可。
delete from [use] where ID=@DelID
END
go
----CCP_DeleparentIDByPKID 6
/*********
ID Name ParentID
3 名称3 1
5 名称5 4
**********/
不知道行不行,你可以试试。
事务
delete from USE u where u.ID in (select ParentID from USE where u.ID = '2')
delete from USE u where u.ID = '2'
试试这个:
delete from tblUSE where ID in
(select ID from tblUSE where ID in
(select ParentID from tblUSE where ID = '3')
UNION
(select ID from tblUSE where ID = '3'))
USE tempdb
go
--父表
CREATE TABLE T_Parent(ParentID INT PRIMARY KEY, --主键,
[NAME] CHAR(20) NOT NULL DEFAULT(''))
GO
--子表
CREATE TABLE T_user(id INT IDENTITY,
[NAME] CHAR(20) NOT NULL DEFAULT(''),
ParentID INT
REFERENCES T_Parent(ParentID) ON DELETE CASCADE --外键,引用外键可以多列,但对应的主键也要是对应的多列且类型要相同。
)
GO
--给外键创建索引
CREATE INDEX ix_ParentID ON T_user(Parentid)
go
SELECT * FROM T_parent
SELECT * FROM T_user
Go
INSERT INTO T_parent SELECT 1,'一年级' UNION ALL SELECT 2,'二年级'
INSERT INTO T_user SELECT '学生1',1 UNION ALL SELECT '学生2',2
go
DELETE FROM T_parent WHERE parentid=1 --删除父表一行,通过父表与子表建立外键级联删除行为,就可以将子表相关行自动删除。
go
SELECT * FROM T_parent
SELECT * FROM T_user
Go
DROP TABLE T_parent,T_user
其他的就不多说了,你可以参考 CREATE TABLE 联机丛书,建议多按F1。
create table #t
(
ID int
)
declare @ID int
select @ID = 1
delete from T Where ID = @ID
insert into #t
select ID from T where ParentID = @ID
while @@Rowcount > 0
begin
delete from T where ID in (select ID from #t)
insert into #t
select ID from T where ParentID in (select ID from #t)
end
--select * from #t
drop table #t
自己写个循环函数,抓出所有的ID,然后
delete table where ID in (函数)