我在sql server中有字符串日期,我想使用ADO.Net检索大于或等于2018年的所有行。这就是我已经完成的工作,但是result.HasRows()
返回false ,尽管该表中已经有行。
与文化有关吗?
更新: 问题出在数据本身。有一些不同格式的日期。现在可以正常工作。
using (var command = connection.CreateCommand())
{
command.CommandText = $"SELECT *
$"FROM [dbo].[tableName] " +
$"WHERE Year(CAST([tableNmae].Date as datetime)) >= {2018} ";
using (var result = command.ExecuteReader())
{
if (result.HasRows)
{
while (result.Read())
{}
}
}
}
答案 0 :(得分:0)
您不能将 CAST 用于字符串类型。您应该使用 CONVERT 而不是 CAST
为什么要104?,因为我以此网站为参考。
http://www.sqlusa.com/bestpractices/datetimeconversion/
using (var command = connection.CreateCommand())
{
command.CommandText = $"SELECT *
$"FROM [dbo].[tableName] " +
$"WHERE Year(CONVERT(DATETIME,[tableNmae].Date,104)) >= {2018} ";
using (var result = command.ExecuteReader())
{
if (result.HasRows)
{
while (result.Read())
{}
}
}
}
注意:要使用CONVERT,该列不能为 ntext 类型。
如果使用它,则会出现此错误。
不允许从数据类型ntext到日期时间的明确转换。
如果您使用的拨号类型不正确,则会显示示例错误