本人自己写的函数,主要实现一张人员表,里面有A,B,C,D,E,F六个人,而我们提供一个总数量比如122,六个人先按每人20个分配,剩余2个数量根据先后顺序分配给A,B各一个。最后结果是A 21, B 21,C 20,D 20,E 20,F 20
-----插入测试表
create table ceshi (yh varchar(10),sl int)
insert into ceshi(yh,sl)
values ('A',0),
('B',0),
('C',0),
('D',0),
('E',0),
('F',0)
----开始建立函数
create function [dbo].[wlzh_cfsl]
(@iquantity int)
returns @temp table(name varchar(20),qty int)
----实现自动拆分行函数
as
begin
DECLARE @ceshi TABLE
( id int identity(1,1),
name varchar(20),
sl int)
insert into @ceshi(name,sl)
select yh,sl from ceshi ----把需要进行计算的表数据插入变量表
declare @count int,@zs int,@sy int,@i int
set @i=1
set @count=(select count(*) from @ceshi) ---6
set @zs=@iquantity/@count --20
set @sy=@iquantity-@zs*@count --0
update @ceshi set sl=@zs
while(@i<=@sy)
begin
update @ceshi set sl=sl+1 where id=@i
set @i=@i+1
end
insert into @temp(name,qty)
select name,sl from @ceshi
return
end
-----测试拆分效果
select * from wlzh_cfsl(122)