转换0000:00:00.00 datetime sql

时间:2013-08-05 08:32:28

标签: sql datetime

我有varchar列,其中保存了datetime,我有一些正常格式00:00:00.00的日期时间,我可以将其转换为日期时间,其他一些格式具有以下格式{ {1}}我无法转换它们。我怎么解决这个问题?我试图转换它,但我得到这些值的错误。

  

选择(DATEPART(HOUR,(SELECT CONVERT(datetime,time,121)FROM表   ))* 3600)+(DATEPART(MINUTE,(SELECT CONVERT(datetime,time,121))   FROM table))* 60)+(DATEPART(SECOND,(SELECT   CONVERT(datetime,time,121)FROM table))))

1 个答案:

答案 0 :(得分:0)

根据提供的信息和0000:00:00.00 = HHHH:MM:SS:NN

的假设
DECLARE @t table (
   blah varchar(20)
);

INSERT INTO @t (blah)
  VALUES ('0:00:00.00')
       , ('0000:00:00.00')
       , ('0000:01:37.61');


SELECT blah
     , hours
     , minutes
     , seconds
     , milliseconds
     , DateAdd(ms, milliseconds, DateAdd(ss, seconds, DateAdd(mi, minutes, DateAdd(hh, hours, 0))))
FROM   (
        SELECT blah
             , Cast(left_part As int) As hours
             , Cast(SubString(right_part, 1, 2) As int) As minutes
             , Cast(SubString(right_part, 4, 2) As int) As seconds
             , Cast(Left(SubString(right_part, 7, 3) + '000', 3) As int) As milliseconds -- padded to 3 characters (trailing zeroes)
        FROM   (
                SELECT blah
                     , SubString(blah, 0, CharIndex(':', blah)) As left_part
                     , SubString(blah, CharIndex(':', blah) + 1, 20) As right_part -- FYI 20 = length of varchar field
                FROM   (
                        SELECT blah
                             , CharIndex(':', blah) + 1 As colon
                        FROM   @t
                       ) As find_the_first_colon
               ) As split_the_string_by_first_colon
       ) As work_out_component_parts;