首页 文章

将Varchar日期转换为Date数据类型

提问于
浏览
1

我有一个列存储SQL Server中数据类型为 varchar 的日期 . 日期格式为 Mon-01-Oct ,表示 Monday, 1st, October .

我希望将数据转换为日期格式为 dd-mm-yy (此处为: 01-10-2018 ),同时将数据插入另一个表中 .

我怎么能做到这一点?

2 回答

  • 2

    我想你可以使用这样的查询:

    -- `monthes` is a raw data you need to do your convertion
    ;with monthes as (
        select '10' mn, 'Oct' md
        union all select '11', 'Nov'
        union all select '12', 'Dec'
        union all select '01', 'Jan'
        union all select '02', 'Feb'
        union all select '03', 'Mar'
        union all select '04', 'Apr'
        union all select '05', 'May'
        union all select '06', 'Jun'
        union all select '07', 'Jul'
        union all select '08', 'Aug'
        union all select '09', 'Sep'
    )
    select parsename(replace(t.dateColumn, '-', '.'), 2) + '-' + m.mn + '-2018' dateString
    from yourTable t
    left join monthes m 
      on m.md= parsename(replace(t.dateColumn, '-', '.'), 1);
    
  • 0

    假设年份应始终在当年,这是一种方法:

    DECLARE @StringDate char(10) = 'Mon-01-Oct'
    
    SELECT CONVERT(Date, 
                   REPLACE(RIGHT(@StringDate, 6), '-', ' ') +' '+ 
                   CONVERT(char(4), GETDATE(), 120),
                   106) As DateValue
    

    结果:

    2018-10-01
    

相关问题