日期:2014-05-17 浏览次数:20642 次
if object_id('Tempdb..#t') is not null drop table #t
create table #t(
[Id] int identity(1,1) not null,
[Num] int null,
[NumOut] int null
)
Insert Into #t
select 4,0 union all
select 5,0 union all
select 8,0 union all
select 6,0
declare @rowcount int --数据条数
declare @i int --计数器
declare @difference int --差
declare @a int --定义的数字
declare @tmp int --临时放定义的数字
set @a=10
set @tmp=@a
select @rowcount=count(1) from #t
set @i=1
while (@i<=@rowcount)
begin
select @difference=Num-@tmp from #t where id=@i
if(@difference>=0)
begin
update #t set NumOut=@difference where id=@i
set @tmp=@a
end
else
begin
update #t set NumOut=Num where id=@i
set @tmp=abs(@difference)
end
set @i=@i+1
end
select * from #t
-------------
--结果
Id Num NumOut
----------- ----------- -----------
1 4 4
2 5 5
3 8 7
4 6&nb