2

我的存储过程:

ALTER procedure [dbo].[performance]
(@startdate nvarchar(100), @enddate nvarchar(100)
as begin
    declare @date1 nvarchar(100) = convert(varchar, @startdate+' 00:00:00.000', 120)

    declare @date2 nvarchar(100) = convert(varchar, @enddate+' 23:59:59.000', 120)

    set NOCOUNT on;
    select l.LocName,v.Vtype, SUM(DATEDIFF(MI,t.Paydate,t.DelDate)) as TotalDiff,
    [dbo].[testfunction](
CONVERT(decimal(10,1), 
AVG( CONVERT(NUMERIC(18,2), DATEDIFF(SS,t.Paydate,t.DelDate) ) )))  as Average
    from Transaction_tbl t
    left join VType_tbl v
        on t.vtid=v.vtid
    left join Location_tbl l
        on t.Locid=l.Locid
    where t.Locid in
        (select t1.Locid from Transaction_tbl t1)
    and dtime between '' + @date1 +'' and ''+ @date2 +''
    and Status =5
    group by v.Vtype,l.LocName,l.Locid order by l.Locid
end

我的功能:

ALTER FUNCTION [dbo].[testfunction] (@dec NUMERIC(18, 2)) RETURNS Varchar(50) 
AS
BEGIN  DECLARE @hour integer,  @Mns integer,   
@second decimal(18,3)DECLARE @Average  Varchar(50)  
select @hour=CONVERT(int,@dec/60/60) 
SELECT @Mns = convert(int, (@dec / 60) - (@hour * 60 ));
select @second=@dec % 60; 

SELECT @Average = convert(varchar(9), convert(int, @hour)) + ':' +  right('00' + convert(varchar(8), convert(decimal(18,2), @Mns)), 2) + ':' +
right('00' + CONVERT(decimal(10,0), convert(varchar(10), @second)), 6)
RETURN @Average end

如果我通过开始日期:2013-06-01 和结束日期:2013-08-01,那么如果我通过开始日期:2010-06-01 和结束日期:2013-08-01(更大的日期差异)然后得到错误:我的功能有什么问题

4

1 回答 1

1

发布您在问题中遇到的确切错误通常是一个好主意。

但是,这是我对可能发生的事情的猜测:我认为错误是由于表达式引起的SUM(DATEDIFF(MI,t.Paydate,t.DelDate)),更具体地说,总值可能超过了带符号的 int 最大值 ( 2147483647)。

这是可能的,因为:

  • DateDiff 函数根据MSDN返回一个有符号整数
  • the difference in minutes for a period of 3 years is approximately 1.5M: (select datediff(mi, '2010-01-01', '2013-01-01') --> 1578240). If you sum up about 2000 such records, it's possible that you exceed the signed int range.

So, if your error is

Arithmetic overflow error converting expression to data type int.

consider converting the minute difference to a data type with a wider range (for example, bigint or numberic(18, 2) as you did with a few rows below).

Concretely, you'll need to replace

SUM(DATEDIFF(MI,t.Paydate,t.DelDate))

with

SUM(convert(numeric(18, 2), DATEDIFF(MI,t.Paydate,t.DelDate)))
于 2013-08-27T12:10:36.200 回答