没看清题意,上面的不对。
create procedure test @a int
as
declare @sl int,@ph char(3)
declare cur cursor for select sl,ph from t order by sl
open cur
fetch next from cur into @sl,@ph
while @@fetch_status = 0 and @a > 0
begin
if @sl >= @a
begin
update t set sl = sl - @a where ph = @ph
set @a = 0
end
else
begin
update t set sl = 0 where ph = @ph
set @a = @a - @sl
end
fetch next from cur into @sl,@ph
end
close cur
deallocate cur
create table t (id int,sl int,ph char(3))
insert t select 1, 100 , '111'
union all select 1 , 200 , '222'
union all select 1 , 300 , '333'
union all select 1 , 400, '444'
go
create procedure test @a int
as
declare @sl int,@ph char(3)
declare cur cursor for select sl,ph from t
open cur
fetch next from cur into @sl,@ph
while @@fetch_status = 0 and @a > 0
begin
if @sl >= @a
begin
update t set sl = sl - @a where ph = @ph
set @a = 0
end
else
begin
update t set sl = 0 where ph = @ph
set @a = @a - @sl
end
fetch next from cur into @sl,@ph
end
close cur
deallocate cur
go
exec test 200
select * from t
id sl ph
----------- ----------- ----
1 0 111
1 100 222
1 300 333
1 400 444
create table t (id int,sl int,ph char(3))
insert t select 1, 100 , '111'
union all select 1 , 200 , '222'
union all select 1 , 300 , '333'
union all select 1 , 400, '444'
alter procedure test @a int
as
declare @sl int,@ph char(3)
declare cur cursor for select sl,ph from t
open cur
fetch next from cur into @sl,@ph
while @@fetch_status = 0 and @a > 0
begin
if @sl >= @a
begin
update t set sl = sl - @a where ph = @ph
set @a = 0
end
else
begin
update t set sl = 0 where ph = @ph
set @a = @a - @sl
end
fetch next from cur into @sl,@ph
end
close cur
deallocate cur
exec test 350
select * from t
id sl ph
----------- ----------- ----
1 0 111
1 0 222
1 250 333
1 400 444