c# - 将天数添加到 DateTime 返回值为 0?

标签 c# sql-server tsql datetime datetime-format

此代码计算 MSSQL 表中日期介于今天和今天 + 8 天之间的记录数,但它不起作用;它返回值 0,但 2 是正确答案。

如果我将 DateTime.Now.AddDays 更改为 7 或更小,它会正常工作。

//Ordre klar til bestilling
command.CommandText = "SELECT COUNT(*) from bestillinger WHERE udlevering BETWEEN @date and @dateadd";
command.Parameters.AddWithValue("@date", DateTime.Now.ToString("dd/MM/yyyy"));
command.Parameters.AddWithValue("@dateadd", DateTime.Now.AddDays(+8).ToString("dd/MM/yyyy"));

con.Open();
command.ExecuteNonQuery();
string result0 = command.ExecuteScalar().ToString();

con.Close();
MessageBox.Show(result0);

if (result0 != "0")
{
    bestillingToolStripMenuItem.ForeColor = System.Drawing.ColorTranslator.FromHtml("#FF1919");
}

最佳答案

不要将日期/时间视为字符串。只是:

command.Parameters.AddWithValue("@date", DateTime.Now);
command.Parameters.AddWithValue("@dateadd", DateTime.Now.AddDays(8));

问题很可能是日期/时间格式。

请注意,您实际上无缘无故地执行了两次;您可以删除 command.ExecuteNonQuery()

最后,不要将整数视为字符串:

int count = (int)command.ExecuteScalar();
if(count != 0)  { .... }

关于c# - 将天数添加到 DateTime 返回值为 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26000114/

相关文章:

c# - 应用程序设计 : NH-session management, 通用存储库,ASP.NET MVC

c# - CaSTLe Windsor - 使用工厂方法注册所有接口(interface)

sql-server - 可以更改 SQL Server 2000 View 中的列长度吗?

sql - 从 SQL 函数获取单个值时如何将 NULL 更改为 0?

tsql - T-Sql @@Identity

c# - 保存 Word 文档

c# - 将十进制变量拆分为整数和小数部分

c# - ITextSharp 添加页码到合并的 pdf 中

asp.net - 避免在 web.config 中提供服务器连接字符串

c# - 如何在数据库中表示逻辑模型?