遇到一个德国的客户,他们的时间格式是JJJJ-TT-DD HH:MM:SS,程序按照这个格式将时间插入数据库,但是在sql自带的转换函数convert、cast过程中报错,网上搜了下都说用convert、cast可以直接转换,但是这个客户的机器就是不行,没有办法自己写了个转换函数,供大家参考:
由于自定义函数里面不能直接使用getdate方法;所以先创建了个获取本地时间的小函数:
create view v_getdate as select getdate() as now_date
然后是转换函数:
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')