我有一个包含分钟时间的列。我要做的是创建一个返回以下格式的函数:
0 = NULL
>0 and <60 mins = '##min'
between 60 mins & 1440 mins = '##hr,##min'
>1440mins = '##days,##hr,##min'
我已经设法使用下面的功能完成了一些操作,但是我正在努力解决如何分割天,小时和分钟的问题:
CREATE FUNCTION dbo.udf_Format_Date_Friendly
(
-- Add the parameters for the function here
@minutes int
)
RETURNS nvarchar(100)
AS
BEGIN
-- Declare the return variable here
DECLARE @Result nvarchar(100)
-- Add the T-SQL statements to compute the return value here
SELECT @Result = CASE WHEN @minutes = 0 THEN ''
WHEN @minutes <= 60 THEN CAST(@minutes AS nvarchar(100)) + ' min'
WHEN @minutes BETWEEN 60 AND 1440 THEN CAST(CAST(@minutes/60 AS INT) AS nvarchar(100)) + ' hr'
ELSE NULL end
-- Return the result of the function
RETURN @Result
END
GO
答案 0 :(得分:1)
尝试;
CREATE FUNCTION dbo.udf_Format_Date_Friendly (@minutes int)
RETURNS nvarchar(100)
AS
BEGIN
return CASE
when @minutes < 60 then cast( @minutes as varchar(10)) + 'min'
when @minutes < 1400 then cast(@minutes/60 as varchar(10)) + 'hr, ' + cast(@minutes%60 as varchar(10)) + 'min'
else cast(@minutes/(1400) as varchar(10)) + 'days, ' + cast((@minutes%1400)/60 as varchar(10)) + 'hr, ' + cast(((@minutes%1400)%60) as varchar(10)) + 'min'
end
end
go
<强>演示强>
;with data(d) as (
select 0 d union all
select 45 d union all
select 80 union all
select 1800
)
select d, dbo.udf_Format_Date_Friendly(d) val
from data
<强>输出强>
0 0min
45 45min
80 1hr, 20min
1800 1days, 6hr, 40min
答案 1 :(得分:0)
逐件方法可能比当前&#34;一个表达式更具可读性,可以做任何事情&#34;格式 - 下面的代码将一次构建一个表达式,从最大(天)开始,一直到分钟级别。
CREATE FUNCTION dbo.udf_Format_Date_Friendly
(
-- Add the parameters for the function here
@minutes int
)
RETURNS nvarchar(100)
AS
BEGIN
-- Declare the return variable here
DECLARE @Result nvarchar(10) = ''
IF @minutes > 1440
BEGIN
SET @Result = @Result + CAST(@minutes/1440 AS NVARCHAR(10)) + ' days, '
END
IF @minutes > 60
BEGIN
SET @Result = @Result + CAST((@minutes%1440) /60 AS NVARCHAR(10)) + ' hr, '
END
IF @minutes > 0
BEGIN
SET @Result = @Result + CAST(@minutes % 60 AS NVARCHAR(10)) + ' min'
END
-- Return the result of the function
RETURN @Result
END
GO