按列值重复行N次,重复次数不限
我在SQL Server 2014中有一个类似的表:
IDSupply Qty PartName
---------------------------
1 2 C
2 4 B
3 50000 A
我想根据带有索引的数量列将每行重复N次(例如,将C从1到4作为索引)
问题是什么:我为这个目标使用了2个查询,但它们只重复了100次,如下所示:
WITH tally AS
(
SELECT 1 n
UNION ALL
SELECT n + 1
FROM tally
)
SELECT partname, n.n Position
FROM supplylist t
JOIN tally n ON n.n <= t.qty
ORDER BY partname, Position
和其他方法可以将每行重复32000次,但我不能将其用作CTE(因为CTE有OPTION(MAXRECURSION 32500)
问题)
WITH Numbers(Num) AS
(
SELECT 1 AS Num
UNION ALL
SELECT Num + 1
FROM Numbers c
WHERE c.Num < 30000
)
SELECT partname, qty, num
FROM supplylist
JOIN Numbers ON supplylist.qty >= Numbers.Num
ORDER BY partname, num
OPTION(MAXRECURSION 32500)
注意:我不能在CTE结构中使用上述代码,如下所示:
WITH Numbers(Num) AS
(
SELECT 1 AS Num
UNION ALL
SELECT Num + 1
FROM Numbers c
WHERE c.Num < 30000
),
CTE as
(
SELECT partname,qty, num
FROM supplylist
JOIN Numbers ON supplylist.qty >= Numbers.Num
ORDER BY partname, num
OPTION(MAXRECURSION 32500)
)
SELECT *
FROM CTE
请帮助我做到这一点,没有限制,没有CTE结构的问题。
解决方案
芬利我找到了解决方案。我们不能在CTE结构中使用"Option(MAXRECURSION 0)",但可以将查询用作函数,并使用"Option(MAXRECURSION 0)"调用和运行如下函数:
Create fnCreateIndex
(
@Pr1 Int
)
RETURNS TABLE
AS
RETURN
(
WITH Numbers(Num) AS
(
SELECT 1 AS Num
UNION ALL
SELECT Num + 1
FROM Numbers c
WHERE c.Num < @Pr1),
CTE as
(
SELECT partname, qty, num
FROM supplylist
JOIN Numbers ON supplylist.qty >= Numbers.Num
)
Select * from cte
)
最后,我们可以使用它来获得结果:
select * from fnCreateIndex (50000) order by partname, num OPTION(MAXRECURSION 0)
我根据https://stackoverflow.com/a/7428903/4885037
找到解决方案相关文章