如何生成 2 级循环
How to Generate 2 Levels Loop
如果我有 2 个变量
- A = 2
- 乙=3
我想生成这样的结果
A | B | Text
1 | 1 | Text1
1 | 2 | Text2
1 | 3 | Text3
2 | 1 | Text4
2 | 2 | Text5
2 | 3 | Text6
我尝试Google并且可以通过此查询达到 1 级
declare @start int = 1
declare @end int = 3
;with numcte
AS
(
SELECT @start as [SEQUENCE]
UNION all
SELECT [SEQUENCE] + 1
FROM numcte WHERE [SEQUENCE] < @end
)
SELECT [SEQUENCE], 'text' + CAST([SEQUENCE] as varchar) as [text] FROM numcte
如何实现 2 级循环?
使用一个数字table(很多例子你可以通过搜索来使用)。生成一个可能大大简化的示例的方法是:
with cte as (
select 1 as num
union all select num + 1 from cte where num < 3 )
select cte.num, cte2.num from cte
cross join cte as cte2
where cte.num in (1, 2)
order by cte.num, cte2.num
;
解决这个问题 - 它可能看起来令人生畏。开始用集合来思考! Fiddle
一个相当简单的方法是:
select a.a, b.b, concat('text', row_number() over (order by a, b))
from (values (1), (2)) a(a) cross join
(values (1), (2), (3)) b(b);
或者如果你真的想声明变量:
declare @a int = 2;
declare @b int = 3;
with n as (
select 1 as n union all
select n + 1
from n
where n < @a or n < @b
)
select na.n as a, nb.n as b, concat('text', row_number() over (order by na.n, nb.n))
from n na join
n nb
on na.n <= @a and nb.n <= @b;
Here 是一个 db<>fiddle.
如果我有 2 个变量
- A = 2
- 乙=3
我想生成这样的结果
A | B | Text
1 | 1 | Text1
1 | 2 | Text2
1 | 3 | Text3
2 | 1 | Text4
2 | 2 | Text5
2 | 3 | Text6
我尝试Google并且可以通过此查询达到 1 级
declare @start int = 1
declare @end int = 3
;with numcte
AS
(
SELECT @start as [SEQUENCE]
UNION all
SELECT [SEQUENCE] + 1
FROM numcte WHERE [SEQUENCE] < @end
)
SELECT [SEQUENCE], 'text' + CAST([SEQUENCE] as varchar) as [text] FROM numcte
如何实现 2 级循环?
使用一个数字table(很多例子你可以通过搜索来使用)。生成一个可能大大简化的示例的方法是:
with cte as (
select 1 as num
union all select num + 1 from cte where num < 3 )
select cte.num, cte2.num from cte
cross join cte as cte2
where cte.num in (1, 2)
order by cte.num, cte2.num
;
解决这个问题 - 它可能看起来令人生畏。开始用集合来思考! Fiddle
一个相当简单的方法是:
select a.a, b.b, concat('text', row_number() over (order by a, b))
from (values (1), (2)) a(a) cross join
(values (1), (2), (3)) b(b);
或者如果你真的想声明变量:
declare @a int = 2;
declare @b int = 3;
with n as (
select 1 as n union all
select n + 1
from n
where n < @a or n < @b
)
select na.n as a, nb.n as b, concat('text', row_number() over (order by na.n, nb.n))
from n na join
n nb
on na.n <= @a and nb.n <= @b;
Here 是一个 db<>fiddle.