SqlServer将bigint类型存储的数据转换为datetime,附带日期检测

SqlServer将bigint类型存储的数据转换为datetime,附带日期检测

-- =============================================
-- Author:		Wiggins
-- Create date: 20200613
-- Description:	bigint转datetime 附带日期有效性检测
-- =============================================
CREATE function [dbo].[fun_ConvertIntToDateTime]
(
	-- 输入参数,具体时间
	@date bigint 
)
returns datetime
AS
BEGIN
	-- Declare the return variable here
	declare @result datetime
    declare @datestr varchar(50)
     set @result = CONVERT(datetime,'1900-01-01')
    set @datestr = CONVERT(varchar,@date)
      IF(len(@datestr)=8)
    begin
       set @datestr=SUBSTRING(@datestr,0,4)+'-'+SUBSTRING(@datestr,4,2)+SUBSTRING(@datestr,6,2)
    end
    else if(len(@datestr)=14)
    begin
	set @datestr=SUBSTRING(@datestr,0,4)+'-'+SUBSTRING(@datestr,4,2)+SUBSTRING(@datestr,6,2)+' '+SUBSTRING(@datestr,8,2)+':'+SUBSTRING(@datestr,10,2)+':'+SUBSTRING(@datestr,12,2)
    end
     else if(len(@datestr)=12)
    begin
	set @datestr=SUBSTRING(@datestr,0,4)+'-'+SUBSTRING(@datestr,4,2)+SUBSTRING(@datestr,6,2)+' '+SUBSTRING(@datestr,8,2)+':'+SUBSTRING(@datestr,10,2)+':00'
    end 
    declare @isdate bit
    select @isdate=ISDATE(@datestr)
    IF(@isdate=1)
    begin
		set @result = CONVERT(datetime,@datestr)
    end
    return @result
END
posted @ 2022-12-03 09:09  星火燎猿*  阅读(338)  评论(0编辑  收藏  举报