[英]Query comparing dates in SQL
我有一张表,上面写着所有发生在 11 月的日期。 我写了这个查询
select id,numbers_from,created_date,amount_numbers,SMS_text
from Test_Table
where
created_date <= '2013-04-12'
此查询应返回在第 11 个月(11 月)发生的所有事情,因为它发生在日期“2013-04-12”(12 月)之前
但它只返回发生在小于 04 (2013- 04 -12) 天的可用日期
难道它只是比较白天的部分? 而不是整个日期?
如何解决这个问题?
Created_date 是日期类型
日期格式默认为yyyy-dd-MM
而不是'2013-04-12',其含义取决于当地文化,使用被认为是文化不变格式的'20130412'。
如果你想与12月4 日比较,你应该写'20131204'。 如果你想与4月12 日比较,你应该写'20130412'。
SQL Server文档中的写国际Transact-SQL语句的文章解释了如何编写文化不变的语句:
使用其他API或Transact-SQL脚本,存储过程和触发器的应用程序应使用未分隔的数字字符串。 例如,yyyymmdd为19980924。
编辑
由于您使用的是ADO,因此最好的选择是参数化查询并将日期值作为日期参数传递。 这样您就可以完全避免格式问题,并获得参数化查询的性能优势。
UPDATE
要在文字中使用ISO 8601格式,必须指定所有元素。 引用datetime文档的ISO 8601部分
要使用ISO 8601格式,必须以格式指定每个元素。 这还包括T,冒号(:)和格式中显示的句点(。)。
......第二个组件的分数是可选的。 时间组件以24小时格式指定。
试试这样吧
select id,numbers_from,created_date,amount_numbers,SMS_text
from Test_Table
where
created_date <= '2013-12-04'
如果您仅与日期值进行比较,则将其转换为日期(而不是日期时间 )将起作用
select id,numbers_from,created_date,amount_numbers,SMS_text
from Test_Table
where
created_date <= convert(date,'2013-04-12',102)
在使用GetDate()函数期间,此转换也适用
你把<=
并且它也将捕获给定的日期。 您可以用<
only替换它。
请尝试以下查询
select id,numbers_from,created_date,amount_numbers,SMS_text
from Test_Table
where
convert(datetime, convert(varchar(10), created_date, 102)) <= convert(datetime,'2013-04-12')
尝试在日期之前和之后使用“#”,并确保您的系统日期格式。 也许“YYYYMMDD O YYYY-MM-DD O MM-DD-YYYY O使用'/ O \\'”
例如:
select id,numbers_from,created_date,amount_numbers,SMS_text
from Test_Table
where
created_date <= #2013-04-12#
日期格式为yyyy-mm-dd。 因此上述查询正在查找早于12Apr2013的记录
建议你通过将日期字符串设置为'2013-04-30'进行快速检查,如果没有sql错误,则确认日期格式为yyyy-mm-dd。
将它们转换为相同格式的日期,然后您可以进行比较。 像这样:
where convert(date, created_date,102) <= convert(date, /*102 is ANSI format*/
substring('2013-04-12',1,4) + '.' + /*year*/
substring('2013-04-12',9,2) + '.' + /*month*/
substring('2013-04-12',6,2) /*day*/
,102)
您还可以使用 to_char(column_name, 'YYYY-MM-DD) 更改格式
下面的查询可用于查找 2013 年 11 月的记录。
Select id,numbers_from,created_date,amount_numbers,SMS_text
from Test_Table
where Month(created_date) = 11 and Year(created_date) = 2013
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.