在 sql 中的另一个 table 的列中插入和填充 table 的方式有几百万行
The way for insert and fill table base on column in another table in sql with Several million rows
我有一个table类似的A有200万条记录
ROW ID ITEM NoOfUnit
1 1 A 2
2 2 B 1
3 3 C 3
.
.
.
我想根据 A 的 NoOfUnit 填充 table B 类似于下面的
ROW ID ITEM QTY
1 1 A 1
2 1 A 1
3 2 B 1
4 3 C 1
5 3 C 1
6 3 C 1
.
.
.
table中的行数B非常大,游标非常慢...
您在这里需要做的就是根据 NoOfUnit
中保存的数字复制您的行,您可以使用数字 table 来完成。然后你 insert
把这个结果放到你的目的地 table.
如何执行此操作的示例如下:
查询
declare @d table(ID int, ITEM char(1),NoOfUnit int);
insert into @d values
(1,'A',2)
,(2,'B',1)
,(3,'C',3)
;
with t as(select t from(values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) as t(t)) -- table with 10 rows
,n as(select row_number() over (order by (select null)) as n from t,t t2,t t3,t t4,t t5) -- cross join 10 rows 5 times for 10 * 10 * 10 * 10 * 10 = 100,000 rows with incrementing value
select d.ID
,d.ITEM
,1 as QTY
from @d as d
join n
on d.NoOfUnit >= n.n
order by d.ID
,d.ITEM;
输出
ID
ITEM
QTY
1
A
1
1
A
1
2
B
1
3
C
1
3
C
1
3
C
1
我只想使用递归 CTE:
with cte as (
select id, item, NoOfUnit, 1 as n
from a
union all
select id, item, NoOfUnit, n + 1
from a
where n < NoOfUnit
)
insert into b (id, item, qty)
select id, item, 1
from cte;
如果 qty
大于 100,则需要 option (maxrecursion 0)
。
我有一个table类似的A有200万条记录
ROW ID ITEM NoOfUnit
1 1 A 2
2 2 B 1
3 3 C 3
.
.
.
我想根据 A 的 NoOfUnit 填充 table B 类似于下面的
ROW ID ITEM QTY
1 1 A 1
2 1 A 1
3 2 B 1
4 3 C 1
5 3 C 1
6 3 C 1
.
.
.
table中的行数B非常大,游标非常慢...
您在这里需要做的就是根据 NoOfUnit
中保存的数字复制您的行,您可以使用数字 table 来完成。然后你 insert
把这个结果放到你的目的地 table.
如何执行此操作的示例如下:
查询
declare @d table(ID int, ITEM char(1),NoOfUnit int);
insert into @d values
(1,'A',2)
,(2,'B',1)
,(3,'C',3)
;
with t as(select t from(values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) as t(t)) -- table with 10 rows
,n as(select row_number() over (order by (select null)) as n from t,t t2,t t3,t t4,t t5) -- cross join 10 rows 5 times for 10 * 10 * 10 * 10 * 10 = 100,000 rows with incrementing value
select d.ID
,d.ITEM
,1 as QTY
from @d as d
join n
on d.NoOfUnit >= n.n
order by d.ID
,d.ITEM;
输出
ID | ITEM | QTY |
---|---|---|
1 | A | 1 |
1 | A | 1 |
2 | B | 1 |
3 | C | 1 |
3 | C | 1 |
3 | C | 1 |
我只想使用递归 CTE:
with cte as (
select id, item, NoOfUnit, 1 as n
from a
union all
select id, item, NoOfUnit, n + 1
from a
where n < NoOfUnit
)
insert into b (id, item, qty)
select id, item, 1
from cte;
如果 qty
大于 100,则需要 option (maxrecursion 0)
。