SQL Datediff存储过程

时间:2015-12-16 01:40:52

标签: sql sql-server stored-procedures datediff

我对我正在尝试设计的存储过程有疑问。

我有一个包含多批交易的表格。当前的表结构如下。我正在尝试编写一个自动负载测试,其中加载状态和加载状态之间的差异小于30分钟。

如果差异是> 30,它将在存储过程创建的表中返回失败。我试图用变量运行它,因为这个存储过程将由一些加载事务的python代码触发。将有大约100个批次ID,因此存储过程需要挖掘大约200行数据。

我试图找出循环是最佳选择,if语句还是两者。任何帮助表示赞赏。

AuditID BatchID  BatchStatus    TimeOccurred
1       TEST_01  Loading        2007-05-10 01:30:00
2       TEST_01  Loaded         2007-05-10 01:59:00
3       TEST_02  Loading        2007-05-10 01:30:00
4       TEST_02  Loaded         2007-05-10 02:00:00
5       TEST_03  Loading        2007-05-10 01:30:00
6       TEST_03  Loaded         2007-05-10 02:05:00

2 个答案:

答案 0 :(得分:2)

考虑到BatchID将有Loading个时间和一个Loaded时间

尝试这样的事情

with cte as
(
select BatchID,
       max(case when BatchStatus ='Loading' then  TimeOccurred END) Loading, -- Min(TimeOccurred)
       max(case when BatchStatus ='Loaded' then  TimeOccurred END) Loaded -- Max(TimeOccurred)
from yourtable 
group by BatchID
),diff as
(
select BatchID,
       datediff(minutes,Loading,Loaded) as Loading_time,
       case when datediff(minutes,Loading,Loaded) > 30 then 'Fail' else 'Pass' End as pass_fail
from cte

答案 1 :(得分:0)

declare @Data table (AuditID int, BatchID  varchar(100), BatchStatus varchar(100), TimeOccured datetime)
insert into @Data (AuditID, BatchID, BatchStatus, TimeOccured) values (1, 'TEST_01', 'Loading', cast('2007-05-10 01:30:00' as datetime))
insert into @Data (AuditID, BatchID, BatchStatus, TimeOccured) values (1, 'TEST_01', 'Loaded', cast('2007-05-10 01:59:00' as datetime))
insert into @Data (AuditID, BatchID, BatchStatus, TimeOccured) values (1, 'TEST_02', 'Loading', cast('2007-05-10 02:00:00' as datetime))
insert into @Data (AuditID, BatchID, BatchStatus, TimeOccured) values (1, 'TEST_02', 'Loaded', cast('2007-05-10 02:35:00' as datetime))

declare @Results table (BatchID  varchar(100), DurationMins int, Success bit)

-- Process each BatchID separately, store results in Results table
declare @BatchID as varchar(100)
Declare @StartTime as datetime
Declare @StopTime as datetime
Declare @MinDiff as int
declare c cursor for 
    select distinct BatchID from @Data
open c
fetch next from c into @BatchID
while @@fetch_status = 0
begin   
    select @StartTime = TimeOccured from @data where BatchID = @BatchID and batchStatus = 'Loading'
    select @StopTime = TimeOccured from @data where BatchID = @BatchID and batchStatus = 'Loaded'
    select @MinDiff = datediff(minute,@StartTime,@StopTime)
    Insert into @Results (BatchID, DurationMins, Success) 
    select @BatchID, @MinDiff, case when @MinDiff > 30 then 0 else 1 end 
    fetch next from c into @BatchID
end
close c
deallocate c
select * from @Results