delete TB where parentid=id and id=1

解决方案 »

  1.   

    技术开发部 的下一级部们是什么parentid?
      

  2.   

    譬如说上表应该删除1,3,4三条记录呀。难道没有SQL语句可以实现此更能吗?
      

  3.   

    1 0 中国
    3 0 加拿大
    4 1 北京
    5 1 上海
    6 1 江苏
    7 6 苏州
    8 7 常熟
    9 6 南京
    10 6 无锡/*
    返回树的某节点的深度
    */
    create function zjm (@id int,@dep int=0)
    returns int 
    as
    begin
    declare @pid int
    select @pid=pid from tb where id=@id
    if isnull(@pid,-1)<>-1
    set @dep=dbo.zjm(@pid,@dep+1)
    return @dep
    end
    go
    select dbo.zjm(5,default)
    select * from tb
    drop function zjmgo
    /*
    求某节点的所有父节点
    */
    create function zjm (@id int,@dep varchar(1000))
    returns varchar(1000) 
    as
    begin
    declare @pid int
    select  @pid=pid from tb where id=@id
    if isnull(@pid,-1)<>-1
    begin
    set @dep= dbo.zjm(@pid,@dep+'|'+cast(@pid as varchar(20)))
    end
    return @dep
    end
    go
    select dbo.zjm(8,'')
    select tb.*,dbo.zjm(tb.id,'') from tb
    drop function zjm/*
    求某节点的所有父节点
    */
    create function zjm (@id int,@dep varchar(1000))
    returns varchar(1000) 
    as
    begin
    declare @pid int
    select  @pid=pid from tb where id=@id
    if isnull(@pid,-1)<>-1
    begin
    set @dep= dbo.zjm(@pid,@dep+'|'+cast(@pid as varchar(20)))
    end
    return @dep
    end
    go
    select * from tb
    /*
    列出每个子接点的所有父接点表
    */
    select a.id,b.id as 'pid',b.name as 'pname'
    from tb a,tb b 
    where charindex(cast(b.id as varchar(100)),dbo.zjm(a.id,''))>0
    order by a.id
    drop function zjm
      

  4.   

    这个没有偷懒的办法了。
    找出最后一层,删除,再找出最后一层,删除。
    一直删除到没有最后一层为止,最后删除该部门。
    要么在数据库做点修改,如下
    ID   ParentID  ParentIDStr   Title               Description
    1     NULL        NULL       研发部              技术研发
    2     NULL        NULL       销售部              商品销售
    3      1           1         设备采购部          负责研发设备的采购
    4      1           1         技术开发部          负责技术的开发研究
    5      4          1,4        技术开发文职        负责技术开发文档管理
    增加了ParentID2,用来纪录它收有的上层,那么删除就可以这样写了:
    declare @id int
    declare @ParentID int
    declare @ParentIDStr varchar(500)
    declare @myLen int
    select top 1 @id=id,@ParentID=IsNull(ParentID,0),@ParentIDStr=ParentIDStr
      from 部门表 
      where id = 你想要的id
    if @ParentID = 0 then
       delete from 部门表 where ID = @id
    else
      begin
        select @myLen = len(@ParentIDStr)
        delete from 部门表 where ID = @id or (left(ParentIDStr,@myLen) = @ParentIDStr)
      end
    这样删除就很简单,不过你就要改一下上层的程序和表结构了.