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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章