SQL For Each - 写入文件

SQL For Each - write to file

所以我们有一个生产 Table 具有以下数据(简单来说)

ID, Item, QTY
1,AAA,3
2,BBB,4

所以 2 个生产任务,一个数量为 3 个,另一个数量为 4 个。我需要一个导出文件 (txt),该文件将显示以下内容

ID,Item
1,AAA
1,AAA
1,AAA
2,BBB
2,BBB
2,BBB
2,BBB

基本上,我需要一个文件,每个数量都有一行。这是因为我使用第 3 方软件,该软件使用文件中的每一行为任务创建 ticket/label。

如有任何帮助,我们将不胜感激。

谢谢,

院长

基本上,你需要一个数字 table,所以你可以这样做:

select p.id, p.item
from production p join
     numbers n
     on n.n <= p.qty;

如果您的 table 有足够的行,那么一种适用于许多数据库的 ANSI 标准方法是:

select p.id, p.item
from production p join
     (select row_number() over (order by p.id) as n
      from production
     ) n
     on n.n <= p.qty;

还有其他特定于数据库的生成数字的方法。

另一种 ANSI 兼容方法是递归 CTE:

with cte (id, item) as (
      select id, item, qty
      from production 
      union all
      select id, item, qty - 1
      from production
      where qty > 0
     )
select id, item
from cte;

(注意:有时需要 recursive 关键字。)