2017-09-18 153 views
-1

我有两个表 - 其中一个名为#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行。

+2

为什么你认为你无法弄清楚?你尝试了什么代码,并得到了什么错误? –

+0

@TabAlleman - 我试了一下,有些东西就是我卡住的地方。我已将代码添加到问题中。 – Elizabeth

+0

从发布的内容来看,这里不需要任何循环。这只是插入可以避免循环的数据。 –

回答

0

当您声明变量@diff时,其值为NULL。

然后立即尝试在循环使用它:

DECLARE @diff INT, @owner_customer_no INT -- Cursor 

WHILE @Iteration <= @diff 

但由于@Iteration是从来没有“小于或等于” NULL,则WHILE循环将不会执行。

编辑:其实,你需要这个循环中移动:

WHILE @Iteration <= @diff 
BEGIN 
... 
SET @Iteration = @Iteration + 1 

END 

里面你的光标,使其执行用于#diff_temp每一行。

编辑2:

这条线之后,

FETCH NEXT FROM loop_cursor INTO @owner_customer_no, @diff 

@Iteration回1,以使得内环将正确下一行从#diff_temp执行。

+0

我已经更新了@diff从1开始 - 循环现在运行,但仍不准确。 – Elizabeth

+0

看我的编辑。把你的外部循环放在光标内,并把你的INSERT放在里面。 –

+0

我做了改变,运行时间很长。我想我碰到了某种无限循环。 。 ...当fetch_status = 0时,获取游标,当迭代<= diff时,插入....设置iteration = iteration + 1,然后获取下一个值。 ...为什么跑这么久。 – Elizabeth