简体   繁体   English

如何从C#比较SQL Server日期时间

[英]How compare SQL Server Datetime from C#

I've got to make a query from C# and compare with a datetime . 我必须从C#中进行查询,并与datetime进行比较。 Datetime is stored in my database like this: 日期时间像这样存储在我的数据库中:

2014-11-09 00:00:01

and I'm using this query: 我正在使用此查询:

SELECT * 
FROM Table 
WHERE DATETIMEVAR = '19/11/2014 0:00:01' AND OTHERVAR = 1

But it's not in the same format. 但这不是相同的格式。 Is there a way to convert from System.DateTime in C# to dates in SQL Server, or a way to cast from SQL Server the datetime in that format?? 有没有一种方法可以将C#中的System.DateTime转换为SQL Server中的日期,或者从SQL Server中以该格式转换日期时间? Should I check with like instead of = in Where clause. 我应该在Where子句中使用like而不是=进行检查。

Thanks. 谢谢。

The best way would be to have a parametrized query in C#, and then set your date time parameter as a datetime (instead of relying on converting dates back and forth to and from strings). 最好的方法是在C#中进行参数化查询,然后将日期时间参数设置为datetime (而不是依赖于来回转换字符串的日期)。

So you should have something like: 因此,您应该具有以下内容:

SELECT * 
FROM Table 
WHERE DATETIMEVAR = @DateTimeValue AND OTHERVAR = 1

and then define that @DateTimeValue parameter as datetime and set it as datetime 然后将该@DateTimeValue参数定义为datetime并将其设置为datetime

That approach: 该方法:

  • prevents any SQL injection vulnerability 防止任何SQL注入漏洞
  • avoid any string/formatting issues - it compares a DATETIME to a System.DateTime in their native format 避免任何字符串/格式问题-它以原始格式比较DATETIMESystem.DateTime

如果要从DateTime对象生成查询,只需执行date.ToString("yyyy-MM-dd HH:mm:ss")即可在查询中将其转换为该格式。

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

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