1

我有'12B17T'准确表示的字符串YYMDDAA是一个不相关的属性)。月份,1-9用于一月至九月;A-C用于 10 月、11 月和 12 月

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

我如何17.11.2012使用 SQL 从中得到类似的东西?

4

4 回答 4

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

这将导致:

|         DT |
--------------
| 2012-11-17 |
于 2012-12-17T10:16:31.927 回答
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演示小提琴在这里

--Results 17-11-2012        
于 2012-12-17T10:17:11.170 回答
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);
于 2012-12-17T10:37:32.340 回答
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

于 2012-12-17T10:46:36.017 回答