简体   繁体   中英

Match date in a varchar column

I have a SQL Server table that stores Time as follows (in a varchar column):

08 SEP 2015 09:15:16
08 SEP 2015 09:15:22
08 SEP 2015 09:15:22
08 SEP 2015 09:15:22
08 SEP 2015 09:15:26
08 SEP 2015 09:15:27
08 SEP 2015 09:15:31

I want to write a query that can give me all entries that are in a particular month and year. Like 'JAN 2016' and so on.

I am using SQL Server.

If, you are not able to change the type of dates that you have then you will need to cast them with format() function to format the date( MMM yyyy ) available from 2012+

SELECT 
       FORMAT(CAST(<column> AS DATE), 'MMM yyyy') as dates
FROM table t

You could also use the datepart() function to filter the dates

WHERE 
DATEPART(MONTH, dates) = 1 and DATEPART(year, dates) = 2015

In order to just the want to display the counts use count() function

SELECT COUNT(*)
FROM table
WHERE DATEPART(MONTH, dates) = 1 AND 
      DATEPART(year, dates) = 2015

As already mentioned in the comments, I would recommend to change this data type to a date/timestamp field in order to avoid risk of data inconsistency and/or having part of your application crashing when trying to convert string (that do not respect the format of a date) to a date object.

Now if and only if it is not feasible in short term , you have two ways to proceed:

1. data conversion:

The first one is to extract all the records from the table and convert them to date type before doing the comparison, however if there is at least one varchar that is not a well formed date , your query will fail.

2. work with string:

Another way of doing is to query your DB directly using a varchar like described hereunder to avoid those conversion issues:

select * from table_A where date_column like '%JAN 2016%'

However query using like are kind of slow and should only be used as a temporary work-around, in long term adapt your data model to ease your life and have a more stable/robust application .

Last but not least, try to run some queries to check if there are not already some wrong data (format or strings that are not dates) inserted in your DB. You might face already some data inconsistency issues.

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