Sql Server string to date conversion

后端 未结 14 709
执笔经年
执笔经年 2020-11-22 09:18

I want to convert a string like this:

\'10/15/2008 10:06:32 PM\'

into the equivalent DATETIME value in Sql Server.

In Oracle, I wou

相关标签:
14条回答
  • 2020-11-22 10:06

    SQL Server (2005, 2000, 7.0) does not have any flexible, or even non-flexible, way of taking an arbitrarily structured datetime in string format and converting it to the datetime data type.

    By "arbitrarily", I mean "a form that the person who wrote it, though perhaps not you or I or someone on the other side of the planet, would consider to be intuitive and completely obvious." Frankly, I'm not sure there is any such algorithm.

    0 讨论(0)
  • 2020-11-22 10:08

    Run this through your query processor. It formats dates and/or times like so and one of these should give you what you're looking for. It wont be hard to adapt:

    Declare @d datetime
    select @d = getdate()
    
    select @d as OriginalDate,
    convert(varchar,@d,100) as ConvertedDate,
    100 as FormatValue,
    'mon dd yyyy hh:miAM (or PM)' as OutputFormat
    union all
    select @d,convert(varchar,@d,101),101,'mm/dd/yy'
    union all
    select @d,convert(varchar,@d,102),102,'yy.mm.dd'
    union all
    select @d,convert(varchar,@d,103),103,'dd/mm/yy'
    union all
    select @d,convert(varchar,@d,104),104,'dd.mm.yy'
    union all
    select @d,convert(varchar,@d,105),105,'dd-mm-yy'
    union all
    select @d,convert(varchar,@d,106),106,'dd mon yy'
    union all
    select @d,convert(varchar,@d,107),107,'Mon dd, yy'
    union all
    select @d,convert(varchar,@d,108),108,'hh:mm:ss'
    union all
    select @d,convert(varchar,@d,109),109,'mon dd yyyy hh:mi:ss:mmmAM (or PM)'
    union all
    select @d,convert(varchar,@d,110),110,'mm-dd-yy'
    union all
    select @d,convert(varchar,@d,111),111,'yy/mm/dd'
    union all
    select @d,convert(varchar,@d,12),12,'yymmdd'
    union all
    select @d,convert(varchar,@d,112),112,'yyyymmdd'
    union all
    select @d,convert(varchar,@d,113),113,'dd mon yyyy hh:mm:ss:mmm(24h)'
    union all
    select @d,convert(varchar,@d,114),114,'hh:mi:ss:mmm(24h)'
    union all
    select @d,convert(varchar,@d,120),120,'yyyy-mm-dd hh:mi:ss(24h)'
    union all
    select @d,convert(varchar,@d,121),121,'yyyy-mm-dd hh:mi:ss.mmm(24h)'
    union all
    select @d,convert(varchar,@d,126),126,'yyyy-mm-dd Thh:mm:ss:mmm(no spaces)'
    
    0 讨论(0)
提交回复
热议问题