Sqlserver
 sql >> Teknologi Basis Data >  >> RDS >> Sqlserver

CTE loop tak terbatas dengan OPTION (maxrecursion 0)

Jika Anda mencapai batas rekursi, Anda memiliki kedalaman yang cukup dalam mensponsori hubungan atau loop dalam data. Kueri seperti berikut ini akan mendeteksi loop dan menghentikan rekursi:

declare @tblMember as Table ( MemberId Int, SponsorMemberId Int );
insert into @tblMember ( MemberId, SponsorMemberId ) values
  ( 1, 2 ), ( 2, 3 ), ( 3, 5 ), ( 4, 5 ), ( 5, 1 ), ( 3, 3 );
declare @MemberId as Int = 3;
declare @False as Bit = 0, @True as Bit = 1;

with Children as (
  select MemberId, SponsorMemberId,
    Convert( VarChar(4096), '>' + Convert( VarChar(10), MemberId ) + '>' ) as Path, @False as Loop
    from @tblMember
    where MemberId = @MemberId
  union all
  select Child.MemberId, Child.SponsorMemberId,
    Convert( VarChar(4096), Path + Convert( VarChar(10), Child.MemberId ) + '>' ),
    case when CharIndex( '>' + Convert( VarChar(10), Child.MemberId ) + '>', Path ) = 0 then @False else @True end
    from @tblMember as Child inner join
      Children as Parent on Parent.MemberId = Child.SponsorMemberId
    where Parent.Loop = 0 )
  select *
    from Children
    option ( MaxRecursion 0 );



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Pemeriksaan Kesehatan SQL Server Proaktif, Bagian 2:Pemeliharaan

  2. EXP() Contoh di SQL Server

  3. Jalankan Prosedur Tersimpan dari Fungsi

  4. Jangan Gunakan sp_depends di SQL Server (Sudah Usang)

  5. Bagaimana cara mengedit tabel untuk mengaktifkan CASCADE DELETE?