简体   繁体   中英

SQL search date range in part of text field

I have a text field in a SQL database with dates that are generally like 13 Jan 1897 but could be just 1962 or Jan 2013 or ?1956 etc.

I want to be able to do a WHERE on year ranges. eg. from 1945 to 1987.

I realise that it may be difficult to cater for all formats of the data. I would be happy if it just catered for: 13 Feb 1972, and Feb 1972, and 1972

Given you are using MySQL. If you want to be able to query your table with proper date comparisons, you may want to create a new field with DATETIME type and fill it with DATETIMES generated from your current field. You'd need queries like :

UPDATE _TABLE_ set NEW_DATETIME_FIELD = STR_TO_DATE(_CURRENT_FIELD_, '%Y') where CHAR_LENGTH(_CURRENT_FIELD_) = 4;

The above query would work for records with values in _CURRENT_FILED_ like '1945'. You'd need to run this query for each type of date string you got in the current field.

The new DATETIME field will allow you to properly use MySQL date functions against it.

If the only date formats you are concerned about are like those above and you just want the Year it looks like you could just use the last 4 characters of the value.

In SQL Server that would be:

RIGHT(datefield,4)

Or in most languages (including SQL Server):

SUBSTRING(datefield,LEN(datefield)-3,4)

In ANSI SQL:

MID(datefield,LEN(datefield)-3,4)

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