1

CTE로 재귀를 수행하고 재귀가 서브 쿼리를 수행하는 데 사용할 수 있도록 변수를 증가시키려는 다음 코드가 있습니다.SQL Server 2008에서 CTE 재귀 내에서 변수를 증가시킬 수있는 방법

WITH cte as 
(
    select @layer as layers, 
    case when exists(select * from #table where [email protected] and string in ('abc','xyz)) then 10 else 0 end 
    union all 
    select layers + 1, total 
    from cte 
    where layers + 1<4 -- 4 is a max number that is unknown and given by the user 
)select * from cte 

#table는 다음과 같은 구조를 가지고 있지만, 데이터 량은 "ABC"또는 "XYZ"중 하나를 갖는 경우, 윌의 포인트를 가지며, 따라서 계층 1에서

string  layer 
abc  1 
xyz  1 
abc  2 
xyz  2 

동적 10 일 때, 레이어 2에서 사용자가 지정한 최대 레이어까지 동일한 작업이 수행됩니다. 재귀에서 포인트와 해당 레벨을 얻고 싶습니다. while 루프와 커서는 금지되어 있습니다. 재귀에서 @layer를 증가시키는 데 문제가 있습니다. 어떠한 제안? 감사합니다

답변

2

재귀에 사용 된 변수를 본 적이 없지만 탤리 테이블로 원하는대로 할 수 있다고 생각합니다. 당신이 정말로 전달 된 @layer 또는 최대 숫자가 큰 경우 많은 느린 될 수 재귀를 사용하여 설정되어있는 경우

if object_id('tempdb..#table') is not null drop table #table 

create table #table (string varchar(64), layer int) 
insert into #table 
values 
('abc',1), 
('abc',2), 
('xyz',2), 
      --missing layer 3 
      --missing layer 4 
('fgh',5), --not in the abc or xyz clause 
('abc',6), 
('xyz',7) --greate than the max passed in via @layer 




declare @layer int = 6 

;WITH 
    E1(N) AS (select 1 from (values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))dt(n)), 
    E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows 
    E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max 
    cteTally(N) AS 
    (
     SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4 
    ) 

select 
    N as Layer 
    ,case when max(layer) is not null then 10 else 0 end 
from 
    cteTally 
    full join #table 
    on N = layer and string in ('abc','xyz') 
where N <= @layer 
group by N 
order by N 

는 여기에 당신이 달성 할 방법이다.

declare @layer int = 6 

;with cte as(
    select 
     1 as layer 
     ,total = case when exists(select * from #table t2 where t2.layer=layer and t2.string in ('abc','xyz')) then 10 else 0 end 
    union all 
    select 
     layer + 1 
     ,total = case when exists(select * from #table t2 where t2.layer=c.layer + 1 and t2.string in ('abc','xyz')) then 10 else 0 end 
    from cte c 
    where layer < @layer) 

select distinct 
    layer 
    ,total = max(total) 
from cte 
group by layer 
order by layer 
+0

대단히 감사합니다! 그것은 작동합니다! – swordgit

+0

땀 없음 @swordgit – scsimon