循环中的MS SQL循环

时间:2017-09-18 18:19:34

标签: sql-server loops insert cursor

我有两个表 - 一个叫做#final,有很多客户数据(所有信息的综合)。十几列左右 - first_name, middle_name, last_name, address, attendees等我还有第二张表

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次,数据输入#final 4次。对于客户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行。

1 个答案:

答案 0 :(得分:0)

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

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

DECLARE @diff INT, @owner_customer_no INT -- Cursor

WHILE @Iteration <= @diff

但由于@Iteration永远不会&#34;小于或等于&#34; 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的下一行。