我有两个表 - 其中一个名为#final,并有很多客户数据(所有信息的组合)。十列左右 - first_name, middle_name, last_name, address, attendees
等我也得到了第二个表循环内的MS SQL循环
create table #diff_temp
(
customer_no int,
num_reception int,
num_guests int,
diff int
)
第二个表中填充了客户ID,总接待服务,门票和diff = reception-guests
之间的差别的方式是什么我需要做的是运行一个循环,并将名称,地址信息插入到#final中,等于每个记录差异的次数。
例如。
#diff_Temp
的数据看起来像这样。
customer_no num_reception num_guests diff
1 5 1 4
2 12 10 2
3 3 1 2
4 32 20 12
5 12 10 2
6 8 6 2
我需要发生的是,有客户1循环的循环运行的4倍,数据输入4次进入#final
。对于客户2,循环将运行2次,客户4将运行12次,以此类推。
对于每个客户,循环运行diff列中值的数量倍数。然后循环根据大型SQL查询将数据插入到#final中。
我似乎无法弄清楚如何使光标或循环在这里工作。
这是我得到的脚本 - 它运行但没有做任何事情。 当我只运行内部游标时,它需要行数(6)并输入每行6次。不是我想要的。
最新更新脚本:
DECLARE @Iteration INT = 1 -- Loop
DECLARE @diff INT = 1 -- Cursor
DECLARE @owner_customer_no INT -- Cursor
BEGIN
DECLARE loop_cursor CURSOR FOR
SELECT owner_customer_no, diff
FROM #diff_temp
OPEN loop_cursor
FETCH NEXT FROM loop_cursor INTO @owner_customer_no, @diff
WHILE @@FETCH_STATUS = 0
BEGIN
SET @Iteration = 1
WHILE @Iteration <= @diff
BEGIN
insert into #final
select distinct
e.customer_no,
0 as guest_cust_no,
h.fname,
...
where e.campaign_no = 1119
and sc.coding_scenario = 2
PRINT @Iteration
PRINT @diff
PRINT @owner_customer_no
SET @Iteration = @Iteration + 1
END
FETCH NEXT FROM loop_cursor INTO @owner_customer_no, @diff
END
CLOSE loop_cursor
DEALLOCATE loop_cursor
END
此代码生成以下
(6 row(s) affected)
iteration 1
diff 4
customer 1
(6 row(s) affected)
iteration 2
diff 4
customer 1
(6 row(s) affected)
iteration 3
diff 4
customer 1
(6 row(s) affected)
iteration 4
diff 4
customer 1
(6 row(s) affected)
iteration 1
diff 2
customer 2
(6 row(s) affected)
iteration 2
diff 2
customer 2
每次迭代/循环插入6行 - 我想要它做的是插入1行。
为什么你认为你无法弄清楚?你尝试了什么代码,并得到了什么错误? –
@TabAlleman - 我试了一下,有些东西就是我卡住的地方。我已将代码添加到问题中。 – Elizabeth
从发布的内容来看,这里不需要任何循环。这只是插入可以避免循环的数据。 –