简体   繁体   English

SQL DATEDIFF 函数返回错误值

[英]SQL DATEDIFF Function returns wrong values

Im executing following sql statement to get the sum values using date difference as a condition.我执行以下 sql 语句以使用日期差异作为条件获取总和值。 "t_QueryDemand" is the table name and "DESIRED_SHIP_DATE" is the value I compare with current system date. “t_QueryDemand”是表名,“DESIRED_SHIP_DATE”是我与当前系统日期比较的值。 But, I always get a date difference higher than 44100, even though the actual difference is between 0-60.但是,我总是得到高于 44100 的日期差异,即使实际差异在 0-60 之间。 DESIRED_SHIP_DATE data type is datetime2(7). DESIRED_SHIP_DATE 数据类型是 datetime2(7)。 I'm using MS SQL server database.我正在使用 MS SQL 服务器数据库。 What could be the issue.可能是什么问题。

Dim curDate As Date = Date.Today()

Dim strSql7DayDemand As date= "SELECT SUM(ORDER_QTY) AS ORDQTY, (TOTAL_SHIPPED_QTY) AS SHIPQTY, DATEDIFF(day," & curDate & ",DESIRED_SHIP_DATE),DESIRED_SHIP_DATE as DIFF from t_QueryDemand where ID='" & Trim(txtPartID.Text) & "' AND DATEDIFF(DAY," & curDate & ",DESIRED_SHIP_DATE) >" & 

在此处输入图片说明

Instead of using a injection use the SQL function GETDATE()使用 SQL 函数 GETDATE() 代替使用注入

DATEDIFF(day,GETDATE(),DESIRED_SHIP_DATE)

This will calculate the date on the server instead of locally like you are currently doing.这将计算服务器上的日期,而不是像您目前在本地执行的那样。

As has been pointed out you have a serious security vulnerability -- you need to use parameterized queries and not string concatenation or you are vulnerable to an SQL injection attack.正如已经指出的那样,您有一个严重的安全漏洞——您需要使用参数化查询而不是字符串连接,否则您很容易受到 SQL 注入攻击。

It will also make your code more robust -- right now you have txtPartID.Text and you are just putting that into your query but what if someone enters an non-number in this field -- you have no way of catching that now.它还将使您的代码更加健壮——现在您有 txtPartID.Text 并且您只是将它放入您的查询中,但是如果有人在此字段中输入一个非数字怎么办——您现在无法捕捉到它。 With a parameterized query of a numeric type you would catch this problem when you converted the data entry to a number.使用数字类型的参数化查询,当您将数据条目转换为数字时,您会发现这个问题。

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

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