课程号   课序号   课程名    先修课课程名  先修课课序号
001      0        C++      
002      0        Java      001           0
003      1        汇编      001           0
004      2        加密解密  003           1
当我想把C++删除后,与它相关的课程都一起删掉,其中要注意:当把C++删掉后,汇编也被删掉,同时加密解密也要被删掉
这好像涉及到递归,请问该语句应该如何写?

解决方案 »

  1.   

    如果是SQL SERVER 2005+ 可以用with表达式declare @table table 
    (id varchar(3),no int,name varchar(8),pid varchar(3),pno int)
    insert into @table
    select '001',0,'C++',null,null union all
    select '002',0,'Java','001',0 union all
    select '003',1,'汇编','001',0 union all
    select '004',2,'加密解密','003',1;with maco as(
    select * from @table where id='001'
    union all
    select a.* from @table a ,maco b where a.pid=b.id

    delete @table 
    from @table a left join maco b on a.id=b.idselect * from @table
      

  2.   

    2005的 cte 先查询子结点 再删除