How to compare dates in SQL Server(如何在 SQL Server 中比较日期)
问题描述
我有一个 HTML 表单,要求用户选择日期,然后点击提交.提交后,我正在尝试使用 ColdFusion 获取所选日期之间的记录.我的查询如下所示:
I have an HTML form where I ask the user to select dates and then hit submit. Upon submitting, I am trying to fetch records between the selected dates using ColdFusion. My query looks like this:
SELECT *
FROM user_activation_events
where STATUS_CODE =1
AND event_date >= #Dateformat(form.from_date, 'dd-mm-yyyy')#
AND event_date <= #Dateformat(form.to_date, 'dd-mm-yyyy')#
但这不起作用,因为日期以这种格式存储在数据库中:
But this does not work as the date is stored in the database in this format:
yyyy-mm-dd hh:mm:ss
谁能告诉我怎么做?
推荐答案
这里有几个问题.任何以 _date 结尾的表单字段都是表单验证条件.所以表单域需要重命名为todate和fromdate.接下来,您最好尝试清理输入.cfqueryparam 用于执行此操作.最后但并非最不重要的一点是,介于两者之间的是更简洁的 SQL 您的查询应该看起来有点像:
There are a couple of issues going on here. Any form field that ends in _date is a form validation criteria. So the form field needs to be renamed todate and fromdate. Next it is good that you are trying to sanitize the input. cfqueryparam is used to do that. Last but not least, between is cleaner SQL Your query should look a little like:
<cfif isDate(form.fromDate) AND isDate(form.toDate)>
<cfquery name="qryUser_Activation_Events">
SELECT *
FROM user_activation_events
WHERE STATUS_CODE =1
AND event_date BETWEEN <cfqueryparam cfsqltype="CF_SQL_date" value="#form.fromDate#">
AND DATEADD(d, 1, <cfqueryparam cfsqltype="CF_SQL_date" value="#form.toDate#">)
ORDER BY ...
</cfquery>
<cfelse>
<!--- Error handling goes here --->
</cfif>
这篇关于如何在 SQL Server 中比较日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 SQL Server 中比较日期
基础教程推荐
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- 带更新的 sqlite CTE 2022-01-01
