0

我有保存varchar的列,datetime我有一些日期时间的正常形式00:00:00.00,我可以转换为日期时间,还有一些其他的格式如下0000:00:00.00,我不能转换它们。我怎么解决这个问题?我试图转换它,但我得到这些值的错误。

select (DATEPART(HOUR, (SELECT CONVERT(datetime,time,121) FROM table)) * 3600) + (DATEPART(MINUTE, (SELECT CONVERT(datetime,time,121) FROM table)) * 60) + (DATEPART(第二,(从表中选择转换(日期时间,时间,121)))))

4

1 回答 1

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;
于 2013-08-05T10:31:27.713 回答