日期:2014-05-19 浏览次数:20728 次
if object_id('[jf]') is not null drop table [jf]
go
create table [jf]([证号] int,[端口] int,[时间标记] datetime,[起日] datetime,[止日] datetime,[状态] varchar(4))
insert [jf]
select 1,1,'2009-03-10 20:19:08.577','2009.3.11','2009.4.10','收视' union all
select 1,1,'2009-04-10 13:21:28.507','2009.4.11','2009.5.10','收视' union all
select 1,1,'2009-05-10 09:18:18.570','2009.5.11','2009.6.10','收视' union all
select 1,1,'2009-06-10 11:08:56.007','2009.6.11','2009.7.10','收视'
go
--select * from [jf]
--创建存储过程:
if object_id('ChaRu','p') is not null
drop proc ChaRu
go
create proc ChaRu(@证号 nvarchar(6),@端口 int,@时间标记 datetime,@起日 datetime,@止日 datetime,@类型 nvarchar(6))
as
set nocount on
--所需数据插入临时表
select 时间标记,起日,止日,状态 into #
from jf
where 证号=@证号 and 端口=@端口
--获取关键的时间点
declare @最小起日 datetime
select @最小起日=min(起日) from jf where 止日>@起日
--插入被撤线时间截断的后一条
insert #
select 时间标记,@止日+1,@止日+30-datediff(d,@最小起日,@起日),状态
from #
where 起日=@最小起日
--更新被撤线时间截断的前一条
update #
set 止日=@起日-1
where 起日=@最小起日
--插入撤线记录
insert # values(@时间标记,@起日,@止日,'撤线')
--将撤线止日之后的日期顺延
update #
set 起日=dateadd(m,datediff(m,@最小起日,#.起日)-1,@止日+31-datediff(d,@最小起日,@起日))
,止日=dateadd(m,datediff(m,@最小起日,#.起日),@止日+30-datediff(d,@最小起日,@起日))
from jf t
where #.起日=t.起日 and t.证号=@证号 and t.端口=@端口 and t.起日>@最小起日
--删除已有记录
delete jf where 证号=@证号 and 端口=@端口
--插入新整合的记录
insert jf
select @证号,@端口,时间标记,起日,止日,状态 from # order by 起日
go
--测试结果:
exec ChaRu 1,1,'2009-06-12 12:32:17.055','2009.4.20','2009.6.3','撤线'
select * from [jf]
/*
证号 端口 时间标记 起日 止日 状态
----------- ----------- ----------------------- -------