简体   繁体   English

varchar列中的匹配日期

[英]Match date in a varchar column

I have a SQL Server table that stores Time as follows (in a varchar column): 我有一个SQL Server表,存储时间如下(在varchar列中):

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. 例如“ JAN 2016”等。

I am using SQL Server. 我正在使用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+ 如果,你是不是能够改变日期的类型,你有,那么你将需要与他们 format()函数来格式化日期(MMM YYYY)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 您还可以使用datepart()函数过滤日期

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

In order to just the want to display the counts use count() function 为了只显示计数,请使用count()函数

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: 1.数据转换:

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. 第一种是提取从表中的所有记录,他们在进行比较之前转换为日期类型,但是如果有至少一个varchar不是一个良好形成的date ,你的查询将失败。

2. work with string: 2.使用字符串:

Another way of doing is to query your DB directly using a varchar like described hereunder to avoid those conversion issues: 另一种方法是使用如下所述的varchar直接查询数据库,以避免这些转换问题:

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 . 但是,使用like查询有点慢,并且只能用作临时解决方法, 从长远来看,应适应数据模型以简化生活,并拥有更稳定/更可靠的应用程序

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. 您可能已经面临一些数据不一致问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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