[英]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
DATETIME
与DateTime.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;
}
}
}
}
DateTime
to a string and then convert it back again. DateTime
转换为字符串,然后再次将其转换回。 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.