【问题标题】:Weird DateTime Format Issue With .NET SqlCommand.AddWithValue() [closed].NET SqlCommand.AddWithValue() 的奇怪日期时间格式问题 [关闭]
【发布时间】:2021-01-05 17:51:10
【问题描述】:

我正在使用参数化查询来读取表:

DateTime date = DateTime.Now.Date;
SqlCommand cmd = new SqlCommand("select top 10 * from Mails  where Date>=@today and Date<@tomorrow");
cmd.Parameters.AddWithValue("@today", date);
cmd.Parameters.AddWithValue("@tomorrow", date.AddDays(1));

在今年年初之前,此查询一直按预期工作。当我使用 SQL Server 探查器检查时,查询被转换为这种格式 YYYY-MM-DD:

select top 10 * from Mails  where Date>='2021-01-05 00:00:00' and Date<'2021-01-06 00:00:00'

但是,SQL Server 似乎期望 YYYY-DD-MM 得到正确的结果。此查询按预期工作:

select top 10 * from Mails  where Date>='2021-05-01 00:00:00' and Date<'2021-06-01 00:00:00'

列数据类型为DateTime。据我所知,.NET 在作为参数传递时会将DateTime 转换为正确的 SQL 格式。而且我以前没有遇到过这样的问题。

我错过了什么?

编辑 1:

这是准确的分析器结果:

exec sp_executesql N'select top 10 * from Mails where Date>=@today and Date<@tomorrow',N'@today datetime,@tomorrow datetime',@today='2021-01-05 00:00:00',@tomorrow='2021-01-06 00:00:00'

SQL Server 返回 us_english 以选择 @@language 但服务器语言和客户端是 tr_turkish。 列的格式是日期时间,这里没有问题。正如我所说,它以前可以正常工作。

【问题讨论】:

  • DateTime 没有格式,它是一个二进制值。 SQL Server 中的 datetimedatetime2datedatetimeoffset 也没有。如果您有格式问题,那是因为 strings 用于存储日期或传递日期参数。解决方案是使用字符串
  • 我要补充一点,奇怪的是,在分析器中你可以看到字符串...参数并复制到Management Studio中查看)
  • C# 查询与 SQL 查询不匹配。您发布的内容不是由这个 C# sn-p 生成的。
  • 不幸的是,Profiler 对参数值进行了自己的格式化,完全独立于网络上实际传递的内容。因为 T-SQL 没有针对 DATETIMEs 的单独文字格式,所以它选择使用 ISO 8601 格式,但它使用 not necessarily safe 格式。这意味着您无法复制粘贴 Profiler 向您显示的内容并期望得到相同的结果,但它意味着您的应用程序确实没有有这个问题,因为它传递了@987654335 @ 作为二进制值。

标签: c# sql .net sql-server


【解决方案1】:

完全跳过参数:

var cmd = new SqlCommand("select top 10 * from Mails  where Date>=cast(cast(current_timestamp as date) as datetime) and Date< cast(dateadd(day, 1, cast(current_timestamp as date)) as datetime)");

再次希望 Sql Server 能够像几乎所有其他数据库一样添加对 current_date 的支持。这将节省一些铸造混乱。

【讨论】:

  • 谢谢,我发现问题出在另一个应用程序输入的数据格式错误。
猜你喜欢
  • 2013-02-21
  • 1970-01-01
  • 2012-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多