为什么下面的Scalar函数返回:*
Create FUNCTION [dbo].[fn_Get_Minute_Hour]
(
@dtStartDate DATETIME ,
@dtEndDate DATETIME
)
RETURNS VARCHAR
AS
BEGIN
DECLARE @DiffSecs INT ,
@Result VARCHAR(100)
SET @DiffSecs = DATEDIFF(SECOND, @dtStartDate, @dtEndDate)
SELECT @Result = CAST(( ( @DiffSecs % 86400 ) / 3600 ) AS VARCHAR(2))
+ ':'
+ CAST(( ( ( @DiffSecs % 86400 ) % 3600 ) / 60 ) AS VARCHAR(2))
RETURN @Result
END
以上功能返回输出如*
预期产出: - MM:HH
答案 0 :(得分:0)
可能是因为VARCHAR
相当于VARCHAR(1)
并且只有一个字符长。将FUNCTION的返回值更改为RETURNS VARCHAR(16)
(或您期望的最大大小)。
您的功能应如下所示:
CREATE FUNCTION [dbo].[fn_Get_Minute_Hour]
(
@dtStartDate DATETIME ,
@dtEndDate DATETIME
)
RETURNS VARCHAR(16)
AS
BEGIN
DECLARE @DiffSecs INT ,
@Result VARCHAR(100)
SET @DiffSecs = DATEDIFF(SECOND, @dtStartDate, @dtEndDate)
DECLARE @sign BIT = CASE WHEN @DiffSecs<0 THEN 1 ELSE 0 END;
SET @DiffSecs=ABS(@DiffSecs)
SELECT @Result =
CASE WHEN @sign=1 THEN '-' ELSE '' END
+ CAST(( ( @DiffSecs % 86400 ) / 3600 ) AS VARCHAR(4))
+ ':'
+ CAST(( ( ( @DiffSecs % 86400 ) % 3600 ) / 60 ) AS VARCHAR(4))
RETURN @Result
END
用以下方法测试:
DECLARE @dtEndDate DATETIME=GETDATE();
DECLARE @dtStartDate DATETIME=DATEADD(MINUTE,13,DATEADD(HOUR,6,DATEADD(DAY,-1,GETDATE())));
SELECT dbo.[fn_Get_Minute_Hour](@dtStartDate,@dtEndDate);
结果
17:47