如何将SQL Server DATETIME
与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;
}
}
}
}
答案 0 :(得分:2)
DateTime
转换为字符串,然后再次将其转换回。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;
}
}
答案 1 :(得分:1)
首先,您的SQL很糟糕。
您正在返回太多数据,并且正在使用隐式联接(当显式联接成为ANSI-SQL的一部分已有近30年了!)
第二,Can we stop using AddWithValue() already?
除了所有这些代码,您还可以对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";
然后,您可以使用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;
}
}