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

私は再帰で使用される変数を見たことはありませんが、あなたは集計表であなたが望むことができると思います。

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 

あなたが本当にその後、ここでは、渡された@layerまたは最大数が多い場合、多く遅くなる可能性がある、再帰を使用して設定されている場合は、あなたがそれを達成する方法をです。

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

関連する問題