日期:2014-05-18 浏览次数:20557 次
貌似跟这个差不多了..自己参考. 問題描述: /*表:@A SN QTY ---------- ----------- 011001 35 022002 27 */ /*需求結果: SN T_NO T_QTY ---------- ----------- ----------- 011001 1 12 011001 2 12 011001 3 11 022002 1 12 022002 2 12 022002 3 3 */ 簡單說下規則。 某种物品(011001)有35件,12件為一打,每一打出一張條碼,條碼有序號(不同物品從1開始),顯示個數為12。 如果最後餘數不夠12件,也要出一張條碼,顯示個數為餘數(例如需求結果T_QTY中的11)。 為方便各位測試寫好了測試數據: DECLARE @A TABLE ( SN NVARCHAR(10), QTY INT ) INSERT INTO @A SELECT '011001',35 UNION ALL SELECT '022002',27 SELECT * FROM @A /* SN QTY ---------- ----------- 011001 35 022002 27 */ DECLARE @A TABLE ( SN NVARCHAR(10), QTY INT ) INSERT INTO @A SELECT '011001',35 UNION ALL SELECT '022002',27 --2005 ;WITH Liang AS ( SELECT SN, QTY, QTY-12 AS A, CASE WHEN QTY>=12 THEN 12 ELSE QTY END AS B, level=1 FROM @A UNION ALL SELECT A.SN, A.QTY, B.A-12, CASE WHEN B.A>=12 THEN 12 ELSE B.A END, level+1 FROM @A AS A JOIN Liang AS B ON A.SN=B.SN AND B.A>0 ) SELECT SN, QTY, B AS T_QTY, level AS T_NO FROM Liang ORDER BY SN,level --2000 SELECT TOP 50 ID=IDENTITY(INT,0,1) INTO # FROM sysobjects; SELECT A.SN, A.QTY, B.ID+1 AS T_NO, CASE WHEN A.QTY-12*B.ID>=12 THEN 12 ELSE A.QTY-12*B.ID END AS T_QTY FROM @A AS A JOIN # AS B ON A.QTY-12*B.ID>0 DROP TABLE # /* SN QTY T_QTY T_NO ---------- ----------- ----------- ----------- 011001 35 12 1 011001 35 12 2 011001 35 11 3 022002 27 12 1 022002 27 12 2 022002 27 3 3 (6 行受影响) */
------解决方案--------------------
--没有测试环境,就只能随手写游标的了。。。。 --当天不生产的没排进去,这个好办的,暂时只排能生产的。。。 --谁帮忙跑下,看看能不能跑过先~~~,哈哈~~ declare @pno varchar(03),@pqty int,@dayqty int,@id int declare @i int, @rate numeric(9,2) set @i=1 set @rate=1.00 declare @t table([day] int, pno varchar(03),aqty int) declare c1 cursor for select pno, pqty, dayqty, id from T open c1 fetch next from c1 into @pno,@pqty,@dayqty,@id while @@fetch_status=0 begin while @pqty>0 begin if @pqty>=@dayqty*@rate begin insert into @t select @i,@pno,@dayqty*@rat