将YYMDD转换为正常日期

时间:2012-12-17 10:06:04

标签: sql sql-server

我的字符串'12B17T'完全代表YYMDDAA是一个无关的属性)。 几个月来,1-9用于1月至9月; A-C用于10月,11月和12月

string的大小是固定的(例如,如果日期是2012年1月1日,它将看起来像'12101T'

如何使用SQL获取17.11.2012之类的内容?

4 个答案:

答案 0 :(得分:2)

这可能是一种丑陋的方式,但我会创建一个函数,您可以在查询中调用它来转换数据:

create function TransformDate(@myString varchar(6))
returns datetime
as
begin

  return cast('20'+left(@myString, 2) +'-'
    + case substring(@mystring, 3, 1)
        when '1' then '01'
        when '2' then '02'
        when '3' then '03'
        when '4' then '04'
        when '5' then '05'
        when '6' then '06'
        when '7' then '07'
        when '8' then '09'
        when '9' then '09'
        when 'A' then '10'
        when 'B' then '11'
        when 'C' then '12' end +'-'
    + substring(@mystring, 4, 2) as datetime)

end

然后你可以这样使用它:

declare @value varchar(6) = '12B17T'

select dbo.transformdate(@value) as dt

请参阅SQL Fiddle with Demo

哪会导致:

|         DT |
--------------
| 2012-11-17 |

答案 1 :(得分:2)

试试这个;

DECLARE @x varchar(50)= '12B17T' 
SELECT  SUBSTRING(@x,4,2) +'-'+ 
   RIGHT( '0' + CASE SUBSTRING(@x,3,1) WHEN 'A' THEN '10'
                          WHEN 'B' THEN '11'
                          WHEN 'C' THEN '12' 
   ELSE SUBSTRING(@x,3,1) END, 2) +'-'+ 
   '20' + SUBSTRING(@x,1,2)

SQL Demo Fiddle here

--Results 17-11-2012        

答案 2 :(得分:0)

如果您的服务器以此格式识别月份,您可以尝试:

SELECT TO_CHAR(t_date,'YYYY.MM.DD') FROM (SELECT TO_DATE(some_date,'YYMMDD') AS t_date FROM some_date_table);

如果没有,那么你必须使用CASE或DECODE:

SELECT dt_year||'.'||dt_month||'.'||dt_day AS date_ FROM
  (SELECT 
     CASE 
      WHEN SUBSTR(some_date,1,2) BETWEEN 0 AND 12 THEN 20||SUBSTR(some_date,1,2)
      WHEN SUBSTR(some_date,1,2) BETWEEN 13 AND 99 THEN 19||SUBSTR(some_date,1,2)
     END AS dt_year,
     CASE 
      WHEN SUBSTR(some_date,3,1) IN('1','2','3','4','5','6','7','8','9') THEN 0||SUBSTR(some_date,3,1)
      WHEN SUBSTR(some_date,3,1) = 'A' THEN '10'
      WHEN SUBSTR(some_date,3,1) = 'B' THEN '11' 
      WHEN SUBSTR(some_date,3,1) = 'C' THEN '12'
     END AS dt_month,
     SUBSTR(some_date,4,2) AS dt_day FROM some_date_table);

答案 3 :(得分:0)

col 是包含字符串 tb3 的表格的列

create table tb3(col varchar(max))
insert into tb3 values('120617T')

declare @tmp varchar(max) 
select @tmp=case 
when substring(col,3,1)='A' then replace(col,'A','10')
when substring(col,3,1)='B' then replace(col,'B','11')
when substring(col,3,1)='C' then replace(col,'C','12') 
when substring(col,3,1)!='0' then replace(col,substring(col,3,1),'0'+substring(col,3,1))
else col end 
from tb3

SELECT CONVERT(VARCHAR(10), convert(datetime,substring(@tmp,1,len(@tmp)-1),109), 104)

<强>输出

<强> 17.06.2012