我有一个消息表,在系统中当用户读取消息系统时会将读取时间添加到数据库中,我想在readTime后1天删除消息但我无法在asp.net部分管理它。如何在cs部分或数据库上处理这种情况(触发器vs。)
我的表
CREATE TABLE [dbo].[Message] (
[messageID] INT IDENTITY (1, 1) NOT NULL,
[ToUserId] NVARCHAR (150) NOT NULL,
[FromUserId] NVARCHAR (150) NOT NULL,
[messageContent] NVARCHAR (MAX) NOT NULL,
[isRead] INT NOT NULL,
[sendingTime] DATETIME NOT NULL,
[readingTime] DATETIME NULL,
PRIMARY KEY CLUSTERED ([messageID] ASC),
FOREIGN KEY ([FromUserId]) REFERENCES [dbo].[Users] ([UserID]),
FOREIGN KEY ([ToUserId]) REFERENCES [dbo].[Users] ([UserID])
);
我的代码
string readDate = "";
String CS2 = ConfigurationManager.ConnectionStrings["StegoDBConnectionString1"].ConnectionString;
SqlConnection con2 = new SqlConnection(CS2);
using (SqlCommand cmd2 = new SqlCommand("select * FROM Message WHERE messageID='" + messageID + "'and isRead=1 ", con2))
{
con2.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd2);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count != 0)
{
readDate = dt.Rows[0]["readingTime"].ToString();
DateTime rDate = Convert.ToDateTime(readDate);
DateTime cDate = Convert.ToDateTime(DateTime.Now);
TimeSpan ts = cDate - rDate;
int days= ts.Days;
if (days > 1) //
{
String CS1 = ConfigurationManager.ConnectionStrings["StegoDBConnectionString1"].ConnectionString;
SqlConnection con1 = new SqlConnection(CS1);
using (SqlCommand cmd1 = new SqlCommand("delete * FROM Message WHERE messageID='" + messageID + "' ", con1))
{
using (SqlDataAdapter sda1 = new SqlDataAdapter(cmd1))
{
con1.Open();
cmd1.ExecuteNonQuery();
}
}
}
}
}
答案 0 :(得分:0)
您应该在闲暇时删除该邮件。 。 。如果有的话。
让我假设您的问题的合理解释涉及一个名为messages
的表,而不是users
。使用表格上的视图:
create view v_messages as
select m.*
from messages m
where m.readtime > dateadd(day, -1, getdate());
如果您使用该视图访问该表,您永远不必担心看到旧邮件。事实上,你可以永远留在那里。此外,您可以在表上安排权限,以便用户只能访问视图而不能访问基础表,从而提供额外的保护。
我想补充一点,日期/时间值应该由数据库添加,而不是应用程序。这在具有多个用户的实际应用程序中尤为重要。您无法控制其计算机上的时钟。
然后,如果您确实要删除邮件,则可以安排作业每天运行一次或每周运行一次,或者每次删除数据库中的旧邮件。
请注意,从表中删除内容可能是一个昂贵的过程 - 锁定行,页面,索引以及整个表。你通常希望在相对安静的时间做这件事。