简体   繁体   English

Datediff 函数()给我错误的答案

[英]Datediff function() giving me wrong answer

I am using SELECT DATEDIFF(DD,$StartDate, $Today) to calculate the number of days between 2 dates.我正在使用SELECT DATEDIFF(DD,$StartDate, $Today)来计算两个日期之间的天数。 $$StartDate is 2020-11-19 and $Today is current date ( $Today = date("Ymd"); ). $$StartDate是 2020-11-19 并且$Today是当前日期( $Today = date("Ymd"); )。 I am getting 28 days as the number of days which is not correct.我得到 28 天作为不正确的天数。 What am I doing wrong?我究竟做错了什么?

To answer the actual question of why the value is "wrong" it's because it isn't ;要回答为什么值“错误”的实际问题,因为它不是 28 is correct for the values you have passed. 28对于您传递的值正确的。 The problem is you aren't parametrising.问题是你没有参数化。 DATEDIFF is actually working completely correctly. DATEDIFF实际上完全正常工作。 What you are doing is the following:您正在做的是以下内容:

SELECT DATEDIFF(DD,2020-11-19, 2021-02-01);

That returns 28 .返回28 That is correct .那是正确的。 What you have is a synonym of the following expressions as well:您所拥有的也是以下表达式的同义词:

SELECT DATEDIFF(DD,1990,2018);
SELECT DATEDIFF(DD,'19050614','19070712');
--and even
SELECT 2018 - 1990;

Because you aren't properly parametrising (and injecting) the value you are passing isn't a datetime value, it's an expression of int s .因为您没有正确参数化(和注入)您传递的值不是日期时间值,所以它是int s的表达式。 Parametrise your query, and pass a date and time date type value, and the SQL works perfectly correctly.对您的查询进行参数化,并传递日期和时间日期类型值,SQL 可以正常工作。 For example:例如:

--This wouldn't be in your SQL, but something equivilent would happen when the parameters are pass from your application
DECLARE @StartDate date = '20201119',
        @Today date = '20210201';
--And the DATEDIFF function
SELECT DATEDIFF(DAY,@StartDate, @Today);

This also returns the correct value for the expression, but also the value you likely expect, 74 .这也将返回表达式的正确值,以及您可能期望的值74

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

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