日期:2014-05-19  浏览次数:20455 次

SQLSERVER 字符 轉 日期
比如字符:   '200706260908015 '   要轉換成日期類型

測試的時候只能
select   cast( '20070626 '   as   datetime)   value
如果加入0908015就會報錯,不知道應該如何才能把 '200706260908015 '整個都轉換為日期????




------解决方案--------------------
2007年6月26号9点8分后面呢?
------解决方案--------------------

create function fn(
@t varchar(20)
)
returns datetime
as
begin
declare @d datetime
set @d=cast(left(@t,8) as datetime)
set @d=dateadd(hh,cast(substring(@t,9,2) as int),@d)
set @d=dateadd(mi,cast(substring(@t,11,2) as int),@d)
set @d=dateadd(s,cast(substring(@t,13,2) as int),@d)
return @d
end
go

declare @date varchar(20)
set @date= '20070626081915 '
select dbo.fn(@date)

drop function fn
------解决方案--------------------
declare @a char(14),@b char(14)
select @a= '20070626090805 ',@b= '20070526070808 '
select abs(datediff(hour,cast(stuff(stuff(stuff(@a,13,0, ': '),11,0, ': '),9,0, ' ') as datetime), cast(stuff(stuff(stuff(@b,13,0, ': '),11,0, ': '),9,0, ' ') as datetime)))
/*
-----------
746

(所影响的行数为 1 行)
*/