简体   繁体   English

在C#/ ASP.NET中将SQL Server DATETIME与DateTime.NOW进行比较

[英]Comparing SQL Server DATETIME with DateTime.NOW in C# / ASP.NET

How do I compare a SQL Server DATETIME with the DateTime.Now value? 如何将SQL Server DATETIMEDateTime.Now值进行比较? As you can see I assigned it to a Session and tried comparing it with DateTime.Now . 如您所见,我将其分配给Session并尝试将其与DateTime.Now进行比较。

string timestamp = @"SELECT sr.*, ud.* FROM SuspensionRecord sr, UserData ud WHERE sr.User_ID=@User_ID AND ud.User_ID=@User_ID";

using (SqlCommand cmd2 = new SqlCommand(timestamp, con))
{
    cmd2.Parameters.AddWithValue("@User_ID", Session["UserID"].ToString());

    using (SqlDataReader dr = cmd2.ExecuteReader())
    {
        if (dr.HasRows)
        {
            while (dr.Read())
            {
                Session["suspensiondate"] = dr["End_Date_Suspension"].ToString();
            }

            if (Convert.ToDateTime(Session["supensiondate"]) >= DateTime.Now.Date)
            {
                lblMessage.Text = "The account's status is suspended.";
                lblMessage.Visible = true;
            }
        }        
    }
}
  1. You should pass in the date and do the comparison in the query instead of in c#. 您应该传递日期并在查询中而不是在c#中进行比较。 That is one less step. 这少了一步。 If you do want to do it in c# then use the appropriate types, do not convert the DateTime to a string and then convert it back again. 如果您确实想在c#中使用适当的类型,请不要将DateTime转换为字符串,然后再次将其转换回。
  2. There is no need for the join (2nd table) in your query 您的查询中无需联接(第二张表)
  3. You do not have to use a DataReader for this, you can use ExecuteScalar which returns 1 value instead. 您不必为此使用DataReader,可以使用ExecuteScalar来返回1值。
  4. Use Add so you can specify the correct schema types with SqlDbType and not AddWithValue 使用Add以便您可以使用SqlDbType而不是AddWithValue指定正确的架构类型
string timestamp = @"SELECT 1 FROM SuspensionRecord sr WHERE sr.User_ID = @User_ID AND supensiondate > @now";
using (SqlCommand cmd2 = new SqlCommand(timestamp, con))
{
    cmd2.Parameters.Add("@User_ID", SqlDbType.Int).Value = Session["UserID"]; // do not convert to string
    cmd2.Parameters.Add("@now", SqlDbType.DateTime).Value = DateTime.Now.Date;
    var result = cmd2.ExecuteScalar();
    if(result != null) // if null then there were no records so account is not suspended
    {
        lblMessage.Text = "The account's status is suspended.";
        lblMessage.Visible = true;
    }
}

First, your SQL is terrible. 首先,您的SQL很糟糕。
You are returning way too much data, and you are using an implicit join (when explicit joins are a part of ANSI-SQL for almost 30 years now!) 您正在返回太多数据,并且您正在使用隐式联接(当显式联接成为ANSI-SQL的一部分已有近30年的历史了!)

Second, Can we stop using AddWithValue() already? 第二, 我们可以停止使用AddWithValue()吗?

Instead of all this code you can do the entire test on SQL and return a single value: 代替所有这些代码,您可以对SQL进行整个测试并返回一个值:

string sql = 
@"SELECT CASE WHEN EXISTS
  (
      SELECT 1 
      FROM SuspensionRecord 
      WHERE User_ID = @User_ID 
      AND End_Date_Suspension >= CAST(GETDATE() AS DATE)
  ) THEN 1 ELSE 0 END";

Then you can use ExecuteScalar instead of ExecuteReader , and you don't need to loop through all the irrelevant data: 然后,您可以使用ExecuteScalar而不是ExecuteReader ,并且不需要遍历所有不相关的数据:

using (SqlCommand cmd2 = new SqlCommand(timestamp, con))
{
    cmd2.Parameters.Add("@User_ID", SqlDbType.Int).Value = Session["UserID"];
    if ((int)cmd2.ExecuteScalar() == 1)
    {
        lblMessage.Text = "The account's status is suspended.";
        lblMessage.Visible = true;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM