表结构
id parentid title
1    0        
2    0
3    1
4    1
5    3
6    3
7    3
8    1
9    0
10   3
需求:
parentid 是记录的上级ID
想用一个sql语句删除id=1 的所有子记录。请哪位大虾赐教!谢谢

解决方案 »

  1.   

    删除后的结果为
    2 0
    9 0
    sql:
    delete TableName where (parentid in (select id from TableName where parentid = 1)) or (id= 1) or (parentid = 1)
      

  2.   

    delete   TableName   where   (parentid   in   (select   id   from   TableName   where   parentid   =   1 or id = 1))   or   (id=   1)   or   (parentid   =   1)
      

  3.   


    declare @t table(ID int,PID int)
    INSERT INTO @t VALUES ('1','0')
    INSERT INTO @t VALUES ('2','0')
    INSERT INTO @t VALUES ('3','1')
    INSERT INTO @t VALUES ('4','1')
    INSERT INTO @t VALUES ('5','3')
    INSERT INTO @t VALUES ('6','3')
    INSERT INTO @t VALUES ('7','3')
    INSERT INTO @t VALUES ('8','1')
    INSERT INTO @t VALUES ('9','0')
    INSERT INTO @t VALUES ('10','3')--使父id为1,此值必须带入
    declare @i int
    set @i=1--定义临时表,分别有ID,父ID,深度lev
    declare @t2 table(ID int,PID int,lev int)
    --先插入一条记录,使得系统变量 @@rowcount>0
    insert @t2 select * ,@i from @t where PID=@iwhile @@rowcount>0
    begin
        set @i=@i+1
        insert @t2 
        select t1.*,@i  from @t2 t2 join @t t1 on t2.ID=t1.PID and t2.lev=@i-1
    end
    select * from @t2delete from @t where [id] in (select [id] from @t2)select * from @t/*
    ID          PID         
    ----------- ----------- 
    1           0
    2           0
    9           0(所影响的行数为 3 行)
    */
      

  4.   

    //注:测试环境:MSSQL 2005--测试数据
    DECLARE @t table(ID int,PID int)
    INSERT INTO @t VALUES ('1','0')
    INSERT INTO @t VALUES ('2','0')
    INSERT INTO @t VALUES ('3','1')
    INSERT INTO @t VALUES ('4','1')
    INSERT INTO @t VALUES ('5','3')
    INSERT INTO @t VALUES ('6','3')
    INSERT INTO @t VALUES ('7','3')
    INSERT INTO @t VALUES ('8','1')
    INSERT INTO @t VALUES ('9','0')
    INSERT INTO @t VALUES ('10','3')
    ----------
    Declare @Id Int 
    Set @Id = 1;    With RootNodeCTE(Id,ParentId) 
    As 

    Select Id,PID From @t Where PID In (@Id) 
    Union All 
    Select B.Id,B.PID From RootNodeCTE A
    Inner Join @t B
    On A.Id = B.PID 

    -----------
    --删除1下的所有结点 
    Delete a from @t a,RootNodeCTE B 
    where A.id=b.id
    --显示结果
    SELECT * from @t
      

  5.   

    /*
    ID          PID         
    ----------- ----------- 
    1           0
    2           0
    9           0(所影响的行数为 3 行)
    */
      

  6.   

    做递归的话,如果用MSSQL 2005,最好用CTE表达式~
    用2K无非就2种方法
    1.楼上写的
    2.用UDF