L
lasmai
Unregistered / Unconfirmed
GUEST, unregistred user!
用存储过程,字段名改成你自己的就可以用了<br><br>CREATE PROCEDURE GetPrice AS<br>declare @st_no varchar(10)<br>declare @st_count int<br>declare @in_count int<br>declare @in_price dec(18, 2)<br>declare @total_count int<br>declare @flag bit<br>declare @total_price dec(18, 2)<br><br>select 编码, 库存, cast(0 as dec(18, 2)) 平均进价 into #tempPrice from 库存表 where 库存 > 0 <br><br>declare stock_cursor cursor for<br>select 编码, 库存 from #tt<br><br>open stock_cursor<br>fetch next from stock_cursor into @st_no, @st_count<br><br>while @@fetch_status = 0<br>begin<br> set @total_count = 0<br> set @flag = 0<br> set @total_price = 0<br><br> declare count_cursor cursor for<br> select 数量, 单价<br> from 进货表<br> where 编码 = @st_no<br> order by 时间 desc<br><br> open count_cursor<br> fetch next from count_cursor into @in_count, @in_price<br> while @@fetch_status = 0 and @flag = 0<br> begin<br> set @total_count = @total_count + @in_count<br> <br> if @total_count >= @st_count<br> begin<br> set @flag = 1<br> set @total_price = @total_price + (@in_count - (@total_count - @st_count))*@in_price<br> end<br> else<br> set @total_price = @total_price + @in_count*@in_price<br> fetch next from count_cursor into @in_count, @in_price<br> end<br> update #tempPrice set 平均进价 = @total_price/@st_count where 编码 = @st_no<br><br> close count_cursor<br> deallocate count_cursor<br><br> fetch next from stock_cursor into @st_no, @st_count<br>end<br>close stock_cursor<br>deallocate stock_cursor<br><br>select * from #tempPrice<br><br>drop table #tempPrice<br>GO