2011-11-08 4 views
0

J'ai une table « tReferences » avec ces champs:récursive procédure stockée dans le serveur SQL 2005

IDFILE [int], 
NAME [varchar(255)], 
IDREFERENCE [int] 

1    FILE1  0 
2    FILE2  0 
3    FILE3  0 
4    FILE4  1 
5    FILE5  4 
6    FILE6  4 
7    FILE7  2 
8    FILE8  3 

Je dois créer une procédure stockée qui récursive peut afficher toutes les références pour un particulier IdFichier.

Résultats:

IDFILE NAME LEVEL 
1    FILE1  0 
4    FILE4  1 
5    FILE5  2 
6    FILE6  2 

Comment puis-je faire cela?

Merci beaucoup.

Répondre

0

Pour cela, je crée une nouvelle table temporaire:

#tempT (
IDFILE [int], 
NAME [varchar(255)], 
IDREFERENCE [int] 
level int 
) 

et je remplir ce tableau ainsi:

declare @parent int; 
declare @level int; 
set @parent = 1 
set @level = 0 

insert into #tempT 
select * from tReferences where IDFILE = @parent 

while @@rowcount > 0 
begin 
    insert into #tempT 
    select *, @level from tReferences 
    where 
     IDREFERENCE in (select IDFILE from #tempT) 
      and 
     IDFILE not in (select IDFILE from #tempT) 
    set @level = @level + 1 

end 

, je reviens

select idfile, name, level from #tempT 
0
create table #tempT (
IDFILE int, 
[NAME] varchar(255), 
[IDREFFERENCE] int, 
[level] int 
) 
declare @idfile int, @idref int, @level int, @flag int; 
    declare @name varchar(max); 
    set @flag=0; 
    set @level=0; 
    DECLARE limit_cursor cursor for 
    select IDFILE,[NAME],IDREFFERENCE FROM tReferences 
    open limit_cursor 
    fetch next from limit_cursor into @idfile,@name,@idref 
    while(@@fetch_status=0) 
    begin 
     if(@idref=0) 
     begin 
      if(@flag=0) 
      begin 
       insert into #tempT values (@idfile,@name,@idref,0); 
       set @flag=1; 
      end 
     end 
     else if(@idref not in (select IDREFFERENCE from #tempT)) 
     begin 
      set @[email protected]+1; 
      insert into #tempT values (@idfile,@name,@idref,@level) 
     end 
     else if(@idref in (select IDREFFERENCE from #tempT)) 
     begin 
      set @level=(select [level] from #tempT where @idref=IDREFFERENCE group by [level]) 
      insert into #tempT values (@idfile,@name,@idref,@level) 
     end 

    fetch next from limit_cursor into @idfile,@name,@idref 
    end 
    close limit_cursor 
    deallocate limit_cursor 
    select IDFILE,[NAME],[level] from #tempT 
    truncate table #tempT 
Questions connexes