sql 自定義函數--固定格式字符轉時間類型

遇到一個德國的客戶,他們的時間格式是JJJJ-TT-DD HH:MM:SS,程序按照這個格式將時間插入數據庫,可是在sql自帶的轉換函數convert、cast過程當中報錯,網上搜了下都說用convert、cast能夠直接轉換,可是這個客戶的機器就是不行,沒有辦法本身寫了個轉換函數,供你們參考:sql

因爲自定義函數裏面不能直接使用getdate方法;因此先建立了個獲取本地時間的小函數: 數據庫

 create view v_getdate as select getdate() as now_date  函數

而後是轉換函數:spa

 1 CREATE  FUNCTION ToDateTime(@DateStr varchar(20))
 2 RETURNS datetime 
 3 AS  
 4 BEGIN 
 5 declare @OutTime datetime
 6 select @OutTime=now_date from v_getdate
 7 if(len(@DateStr)<20)
 8   set @DateStr=substring(@DateStr+' 00:00:00',1,20)
 9 set @OutTime=dateadd(year,0-year(@OutTime)+cast(substring(@DateStr,1,4) as int),@OutTime)
10 set @OutTime=dateadd(month,0-month(@OutTime)+cast(substring(@DateStr,6,2) as int),@OutTime)
11 set @OutTime=dateadd(day,0-day(@OutTime)+cast(substring(@DateStr,9,2) as int),@OutTime)
12 set @OutTime=dateadd(hour,0-DATEPART(HH,@OutTime)+cast(substring(@DateStr,12,2) as int),@OutTime)
13 set @OutTime=dateadd(minute,0-DATEPART(N,@OutTime)+cast(substring(@DateStr,15,2) as int),@OutTime)
14 set @OutTime=dateadd(second,0-DATEPART(S,@OutTime)+cast(substring(@DateStr,19,2) as int),@OutTime)
15 return @OutTime
16 END

 調用示例:select dbo.ToDateTime('2014-04-05 06:07:08')code

相關文章
相關標籤/搜索