【发布时间】:2018-04-21 11:46:55
【问题描述】:
我有一个消息表,在系统中,当用户阅读消息时系统会将阅读时间添加到数据库中,我想从 readTime 中删除 1 天后的消息,但我无法在 asp.net 部分管理它.我如何在 cs 部分或数据库上处理这种情况(触发器与)
我的桌子
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();
}
}
}
}
}
【问题讨论】:
-
例如每天运行一次的作业,它将查找并删除所有早于 ... 的消息或简单的过期日期列和不会显示过期消息的应用程序。
-
你的问题毫无意义。您说要从“消息”中删除,但您显示了一个名为“用户”的表。你说要使用
ReadTime,但是表里只有BlockedTime。 -
@GordonLinoff 抱歉复制错误我已修复此问题。
标签: sql asp.net sql-server