日期时间方程式不返回值.sql server 2008

本文关键字:sql server 2008 返回值 时间 方程式 日期 | 更新日期: 2023-09-27 18:28:26

string s=@"从Bill_Detail中选择*,其中账单日期='"+mcCalendar.SelectionStart.ToShortDateString()

所以我有这个代码。由于toshortdatestring,mcCalendar的值为"8/20/2013"。我只需要获取日期的所有行,mcCalendar。

所以是

从Bill_Detail中选择*,其中账单日期时间="2013年8月20日"

数据库表上的账单日期时间是一种日期时间数据类型。sqlserver 2008

为什么我不能用这个代码得到我期望得到的行?

日期时间方程式不返回值.sql server 2008

我的猜测是,由于文化原因,ToShortDateString实际上并没有返回您想要的值。正确的修复方法不是更改文本处理,而是使用参数化查询:

string sql = "select * from Bill_Detail where DateTimeofBilling=@QueryDate";
using (var command = new SqlCommand(sql, conn))
{
    command.Parameters.Add("@QueryDate", SqlDbType.Date).Value = 
        mcCalendar.SelectionStart.Date;
    // Execute the command
}

始终使用参数化查询,而不是构建包含值的SQL字符串:

  • 它可以避免SQL注入攻击
  • 它避免了像这样的数据转换问题
  • 它有助于将代码(SQL)与数据分离,从而更容易查看发生了什么
string s = @"select * from Bill_Detail where DateTimeofBilling=CONVERT(date, '" + mcCalendar.SelectionStart.ToShortDateString() + "'); "

应该做你想做的事(你最后没有结束语)。但是,参数化查询是一种更好的方法。

查看以下代码是否返回结果。如果字段的命名正确,您可能会专门查找不进行转换的"08/20/2013 12:00:00"。

select * from Bill_Detail where CONVERT(date, DateTimeofBilling)='08/20/2013';

这是因为您已经从where子句中删除了时间元素。

例如,如果您的值为:"8/20/2013 00:00:00",那么它将需要一个完整的DateTime参数。

有几种方法可以修复它。

1) 使用以下SQL:

string s = @"select * from Bill_Detail where DateTimeofBilling like '"
+ mcCalendar.SelectionStart.ToShortDateString() + "%'";

2) 删除"ToShortDateString",使您传递的参数是完整的日期和时间(mcCalendar.SelectionStart=8/20/2013 00:00:00)

string s = @"select * from Bill_Detail where DateTimeofBilling = '"
    + mcCalendar.SelectionStart + "'";

如果您的服务器配置为英国式日期(dd/mm/yyyy)而不是美国式日期(mm/dd/yyyy。请尝试将日期指定为"dd-mmm-yyyy"。

string queryDate = mcCalendar.SelectionStart.Date.ToString("dd-MMM-yyyy");
string s = "SELECT * FROM Bill_Detail WHERE DateTimeofBilling = '" + queryDate + "'";