设为首页 加入收藏

TOP

T-SQL自定义函数ConvertSecondsToTime
2014-11-24 00:13:05 来源: 作者: 【 】 浏览:12
Tags:T-SQL 定义 函数 ConvertSecondsToTime

MS SQL Server一个自定义函数[dbo].[udf_ConvertSecondToTime],把秒数转换为时间。
传入的值最大为86399,如果大于这个数值,这将会出现异常:
The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value.
udf_ConvertSecondToTime
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Insus.NET
-- Create date: 2012-03-24
-- Description: Convert second to time
-- =============================================
CREATE FUNCTION [dbo].[udf_ConvertSecondToTime]
(
@Seconds INTEGER
)
RETURNS TIME
AS
BEGIN
DECLARE
@H AS NVARCHAR(2) = CAST(ROUND(@Seconds / 3600, 0) AS NVARCHAR),
@M AS NVARCHAR(2) = CAST(ROUND(((@Seconds % 3600) / 60),0) AS NVARCHAR),
@S AS NVARCHAR(2) = CAST(ROUND(((@Seconds % 3600) % 60),0) AS NVARCHAR)
RETURN CAST((@H + ':' + @M + ':' + @S) AS TIME)
END
Example:
SELECT [dbo].[udf_ConvertSecondsToTime](477)
SELECT [dbo].[udf_ConvertSecondsToTime](86399)
Result:


作者 Insus.NET
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇10分钟把永远跑不完的存储过程变.. 下一篇T-SQL、Jet SQL和PL-SQL各自的含义

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: