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

sql 查询多重递归
现有表两个


合同表 合同续期表
id Id
编号 续期日期
  新合同Id
  旧合同Id



现在需求是 需要拿到每份合同最后一次的续期合同 如客户2000年1月与我签订合同有效期1年,在2001年的时候客户续期2年 则 有效期 为2001年-2003年 ,当2003年的时候 客户再续期 5年 则有效期为 2003-2008年一月 现在想拿到 2003-2008年这份合同 

上面的需求是拿单份合同的最后续期一份合同(以前是单递归实现)

现在的需求是拿到所有合同的最后一份续期合同 求解答

------解决方案--------------------
SQL code
if object_id('t1')is not null
drop table t1
go
 create   table   t1  
  (    
      id   int   identity(1,1),  
      code   int,  
      parentcode   int  
  )  
  go  
  insert   t1   select   1,null  
  union   all   select   2,1  
  union   all   select   3,1  
  union   all   select   4,2   
    union   all   select   5,3
      union   all   select   6,4
        union   all   select   7,5
   go
   
  if   exists   (select   *   from   dbo.sysobjects   where   id   =   object_id(N'[dbo].[f_cid]')   and   xtype   in   (N'FN',   N'IF',   N'TF'))  
  drop   function   [dbo].[f_cid]  
  GO   
 
  create   function   f_cid(  
  @id   int  
  )returns   @re   table(code   int,[level]   int)  
  as  
  begin  
  declare   @l   int  
  set   @l=0  
  insert   @re   select   @id,@l  
  while   @@rowcount>0  
  begin  
  set   @l=@l+1  
  insert   @re   select   a.code,@l  
  from   [t1]   a,@re   b  
  where   a.parentcode=b.code   and   b.[level]=@l-1  
  end  
  return  
  end  
  go  
   
   select * from t1
  --调用(查询所有的子)  
  select   a.*,层次=b.[level]   from   [t1]   a,f_cid(2)b   where   a.code=b.code  
  go