C#SQL Server比较日期与字符串 [英] C# SQL Server compare date with string
问题描述
我必须将一个表字段(该日期字段是以var / char / yyyy格式存储为varchar的日期)与一个日期值进行比较,但是比较失败。我有例外
I have to compare a table field that is a date stored as varchar in the format 'dd/MM/yyyy' with a date value, but the comparison fails. I have exception
从字符串转换日期和/或时间时转换失败。
我尝试转换日期以比较nstring,例如
Conversion failed when converting date and/or time from character string. I tried converting the date to compare i nstring, like this
string dateFormat = date.ToString("dd/MM/yyyy");
然后编写如下查询:
string sql = "select * from TB_RICHIESTE where CONVERT(DATE, Date) <= CONVERT(DATE, '" + dateFormat + "')";
但是我有这个想法。有人可以帮助我吗?谢谢
But I have this excpetion. Someone can help me? Thanks
推荐答案
首先,您不应将日期存储为字符串。
正如Panagiotis Kanavos在评论中写道-这是一个严重的错误。您无法按此类列进行排序,也无法搜索日期范围,最重要的是-您无法控制某人是否输入了无效值-没有什么可以阻止某人输入 Alfredo
有关更多信息,请阅读亚伦·贝特朗(Aaron Bertrand)的坏习惯:选择错误的数据类型。
第二,您不应将日期从.Net传递到SQL Server作为字符串。您应该将DateTime的实例作为参数传递。
.Net DateTime
直接映射到SQL Server的 日期
。
Second, you should not pass dates from .Net to Sql server as strings. you should pass instances of DateTime as parameters.
The .Net DateTime
maps directly to SQL Server's Date
.
如果您无法更改列的数据类型,则至少可以使用适当的格式将其转换为日期转换样式(您的情况为103)。
If you can't change the data type of the column, you can at least convert it to date using the proper convert style (103 in your case).
以下是一种更好的方法:
Here is a better way to do it:
var sql = "select * from TB_RICHIESTE where CONVERT(DATE, [Date], 103) <= @Date";
然后将 @Date
参数添加到 SqlCommand
:
com.Parameters.Add("@Date", SqlDbType.Date).Value = date.Date;
这篇关于C#SQL Server比较日期与字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!