日期:2014-05-17 浏览次数:20721 次
CREATE TABLE #TEMP(D VARCHAR(20),QTYI INT,ID INT DEFAULT 0) insert #TEMP(D,QTYI) select 'A',1 union all select 'A',4 union all select 'A',3 union all select 'A',3 union all select 'A',5 union all select 'A',2 union all select 'A',3 UNION ALL SELECT 'A',5 DECLARE @INT INT =20 UPDATE #TEMP SET ID=case when QTYI-@INT>0 then qtyi else 0 end , @int=case when QTYI-@INT >0 then 0 else @INT-qtyi end where @INT>0 select * from #TEMP DROP TABLE #TEMP
CREATE TABLE #TEMP(D VARCHAR(20),QTYI INT,ID INT DEFAULT 0) insert #TEMP(D,QTYI) select 'A',1 union all select 'A',4 union all select 'A',3 union all select 'A',3 union all select 'A',5 union all select 'A',2 union all select 'A',3 UNION ALL SELECT 'A',5 DECLARE @INT INT ,@qty int,@n int select @Int=20,@qty=0,@n=0 UPDATE #TEMP SET ID=case when @int>0 then case when @INT>=QTYI then qtyi else @INT end else 0 end, @int=case when @INT>=@qty then @INT-@qty else 0 end, @qty=qtyi select * from #TEMP --DROP TABLE #TEMP /*D QTYI ID -------------------- ----------- ----------- A 1 1 A 4 4 A 3 3 A 3 3 A 5 5 A 2 2 A 3 2 A 5 0 (所影响的行数为 8 行)
------解决方案--------------------
在定义一个变量
CREATE TABLE #TEMP(D VARCHAR(20),QTYI INT,ID INT DEFAULT 0) insert #TEMP(D,QTYI) select 'A',1 union all select 'A',4 union all select 'A',3 union all select 'A',3 union all select 'A',5 union all select 'A',2 union all select 'A',3 UNION ALL SELECT 'A',5 DECLARE @INT INT =20,@a int UPDATE #TEMP SET @a=@INT, @INT=@INT-QTYI, ID=case when @INT>0 then QTYI when @a>0 and @INT<0 then qtyi+@INT else 0 end select * from #TEMP DROP TABLE #TEMP