日期:2014-05-18 浏览次数:20653 次
--分析没错,不知执行有没有错,没建表,试下
create trigger [流水表_updins]
on [流水表]
for insert
as
update 余额表
set 货物余额=货物余额+i.货物进出量
from inserted i
where 余额表.货物名称=i.货物名称
and i.进出方向='进货'
and convert(varchar(10),i.货物进出时间,111)=convert(varchar(10),余额表.货物进出时间,111)
insert into 余额表
select 货物名称,货物进出量,货物进出时间
from inserted i
where not exists (select 1 from 余额表
where 余额表.货物名称=i.货物名称
and convert(varchar(10),i.货物进出时间,111)=convert(varchar(10),余额表.货物进出时间,111))
and i.进出方向='进货'
--你的出货时间就按晚于所有进货的来计算
declare @proname nvarchar(50),@qty float
declare cur cursor local for select 货物名称,货物进出量=sum(货物进出量) from inserted i where i.进出方向='出货'
open cur
fetch next from cur into @proname,@qty
while @@fetch_status=0
begin
declare @tmpqty float,@tmpdate varchar(10)
while exists(select 1 from 余额表 where 货物进出量>0) and @qty>0
begin
select top 1 @tmpqty=货物进出量,@tmpdate=convert(varchar(10),货物进出时间,111)
from 余额表
where 货物进出量>0 and 货物名称=@proname
order by 货物进出时间 asc
if(@qty>@tmpqty)
begin
delete 余额表 where 货物名称=@proname and convert(varchar(10),货物进出时间,111)=@tmpdate
select @qty=@qty-@tmpqty
end
else
begin
update 余额表 set 货物进出量=货物进出量-@qty where 货物名称=@proname and convert(varchar(10),货物进出时间,111)=@tmpdate
delete 余额表 where 货物名称=@proname and convert(varchar(10),货物进出时间,111)=@tmpdate and 货物进出量=0
select @qty=@qty-@tmpqty
end
end
fetch next from cur into @proname,@qty
end
close cur
deallocate cur
go
------解决方案--------------------
create trigger tri_l_u_i
on lius
for insert
as
declare @type char(2),@total int,@date datetime,@cName char(10),@con int,@i int ,@t int
select @cName=cName,@total=total,@date=date,@type=ctype from inserted
if @type='入'
begin
if exists(select 1 from yue where cName=@cName and date=@date)
update yue set total=total+@total where cName=@cName and date=@date
else
insert into yue values(@cName,@total,@date)
end
if @type='出'
begin
select @t=sum(total) from yue where cName=@cName
if @total>@t
return
while @total>0
begin
select top 1 @con=total,@date=date from yue where cName=@cName order by date asc
if @con>=@total
begin
select @con=@con-@total,@total=0
update yue set total=@con where cName=@cName and date=@date
end
else
begin
select @total=@total-@con,@con=0
delete yue where cName=@cName and date=@date
end
end
end
----------------------------------------
--测试表结构:
create table yue
(
cName char(10),
total int,
date datetime
)
create table lius
(
cName char(10),
total int,
date datetime,
ctype char(2)
)
insert into yue select '轴承','100','2012-05-01' union all
select '端盖','200','2012-06-01' union all
select '轴承','200' ,'2012-07-01'union all
select '轴承', '330', '2012-08-01'union all
select