简体   繁体   中英

How to extract a date from a string in SQL?

I have a very simple tag in a table, structured as tag-DDMMYY. I want to convert that into a date, MM-DD-20YY. Is there an easy way to do this in SQL?

I'm not an expert developer and I feel like this should be quite easy using PatIndex (there's always only one dash), but I've got nowhere so far and I'm hoping someone expert could help.

This is mysql

You can use some date and string function

select  str_to_date(substr(my_column, LOCATE('-', my_column), 50),%d%m%y)
from you_table ;

In MSSQL, you can do something like:

SELECT SUBSTRING(T1.OriginalDate, PATINDEX('%-%', T1.OriginalDate)+3, 2) 
     + '-' 
     + SUBSTRING(T1.OriginalDate, PATINDEX('%-%', T1.OriginalDate)+1, 2) 
     + '-' 
     + '20' + SUBSTRING(T1.OriginalDate, PATINDEX('%-%', T1.OriginalDate)+5, 2) 
     AS NewFormatDate
FROM (SELECT 'tag-310516' as OriginalDate) T1

Try this..(SQL Server)

  select cast (stuff(stuff(substring(column,patindex('%-%',column)+1,len(column)),5,0,'.20'),3,0,'.') as date) 
   from mytable

Borrowed from here

For mysql you can try something like this

select str_to_date(concat(substring(yourcolumn,instr(yourcolumn,'-')+1,4),'20',substring(yourcolumn,length(yourcolumn)-1,2)),'%d%m%Y')
from yourtable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM