if exists (select * from sysobjects where id = object_id('dbo.R_P_GetNewRrdTime_PROC') and sysstat & 0xf = 4)
drop procedure dbo.R_P_GetNewRrdTime_PROC
GO
create PROCEDURE [dbo].[R_P_GetNewRrdTime_PROC](
@startTime smalldatetime,
@duration int,
@tblName varchar(20),
@newrecord_startTime smalldatetime output,
@newrecord_endtime smalldatetime output)
AS
BEGIN
--临时变量,用来存放从表中查询出的duration
declare @tmp_duration int;
--临时变量,用来存放从表中查询出的表中的最新时间
declare @max_time smalldatetime;
--总的sql语句
declare @execSql nvarchar(1000);
--变量定义语句
DECLARE @ParmDefinition nvarchar(500);
set @newrecord_endtime = @startTime;
--获取表中最新的时间信息
set @execSql= N'select @max_time = max(BeginTime) from ' +@tblName;
set @ParmDefinition = N'@max_time smalldatetime output';
EXEC sp_executesql @execSql,@ParmDefinition,@max_time output
--表中最近时间大于等于要生成数据,说明数据已经存在了,则看看Duration是否与当前一致,一致就退出,不一致就修改。
if (@max_time >= @startTime)
begin
set @execSql= N'select @tmp_duration = avg(Duration) from '+@tblName+' where BeginTime=' + convert(char(10),@startTime,120);
set @ParmDefinition = N'@tmp_duration int output';
print 'start exec' ;
EXEC sp_executesql @execSql,@ParmDefinition,@tmp_duration=@tmp_duration output
if (@tmp_duration IS NULL)
begin
set @newrecord_startTime= @startTime
end
else
begin
if (@tmp_duration = @duration)
begin
print 'current data is correct, not need to insert data. begintime=' + convert(varchar(19),@startTime,20)
return --直接返回
end
else
begin
update R_P_BscBase set Duration=@duration where BeginTime=@startTime
return --更新duration后直接返回
end
end
end
else
begin
--如果存在时间为空,则该表中没有数据,需要造一个星期至当前的数据
if(@max_time IS NULL)
begin
set @newrecord_startTime=DATEADD(day,-17,@startTime);
set @newrecord_startTime=convert(smalldatetime,convert(char(11),@newrecord_startTime,120)+'00:00:00')
end
--表中最近时间在收到的时间17天内,从表中最近时间开始生成。
if (@max_time < @startTime and DATEADD(day,17,@max_time) >= @startTime)
begin
print '表中最近时间在收到的时间17天内';
set @newrecord_startTime=DATEADD(minute,@duration,@max_time);
if(@newrecord_startTime > @startTime)
begin
set @newrecord_startTime=@startTime;
end
end
--表中最近时间在收到的时间17天外,则考虑是时间跳变,此时插入当前一条数据
if (DATEADD(day,17,@max_time) < @startTime)
begin
set @newrecord_startTime=@startTime;
--从表中最近17天时间开始生成,暂时屏蔽
-- set @newrecord_startTime=DATEADD(day,-17,@startTime);
-- set @newrecord_startTime=convert(smalldatetime,convert(char(11),@newrecord_startTime,120)+'00:00:00')
end
end
END
go
调用方法
exec R_P_GetNewRrdTime_PROC @startTime, @duration, tblabc, @newrecord_startTime out, @newrecord_endtime out