C# 如何在一定时间后自动删除sql server中的记录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18275386/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:46:20  来源:igfitidea点击:

How to automatically delete records in sql server after a certain amount of time

c#sqlasp.netsql-serverdatabase

提问by Master Yoda

I have set up temporary user accounts on my sql database where the user names, passwords and date added of my websites users are stored.

我已经在我的 sql 数据库上设置了临时用户帐户,其中存储了我的网站用户的用户名、密码和添加日期。

I was initially going to have these records delete programmatically but now im wondering if sql server 2008 has a built in function that allows records to be auto-deleted after lets say one day.

我最初打算以编程方式删除这些记录,但现在我想知道 sql server 2008 是否具有内置功能,允许在一天后自动删除记录。

This would resolve the issue of a user being able to stay logged into the system after their temporary account is closed

这将解决用户在其临时帐户关闭后仍能登录系统的问题

thanks

谢谢

采纳答案by Gordon Linoff

You might be able to get what you want without actually deleting the records. You can add a computed column into the table to say whether the record is valid.

您可能无需实际删除记录即可获得所需内容。您可以在表中添加一个计算列来说明记录是否有效。

 IsValid as (case when getdate() - CreatedAt > 1 then 0 else 1 end)

You can also do this for key fields in the record, so you cannot find them:

您也可以对记录中的关键字段执行此操作,因此您找不到它们:

_name varchar(255),
name as (case when getdate() - CreatedAt < 1 then _name end)

You can then use a view to access the table:

然后,您可以使用视图访问该表:

create vw_Logins as
    select name, . . .
    from t
    where isValid = 1;

Then, at your leisure, you can actually remove the rows if you need to for performance reasons.

然后,在闲暇时,如果出于性能原因需要,您实际上可以删除行。

EDIT:

编辑:

You don't actually need a computed column, if you phrase the view as:

如果您将视图表述为:

create vw_Logins as
    select name, . . .
    from t
    where getdate() - CreatedAt < 1;

回答by Sam Leach

Create a Stored Procedure to do it and then schedule the SPROCs running as explained here.

创建一个存储过程来执行此操作,然后按照此处的说明安排运行的 SPROC 。

DELETE FROM myTable
WHERE timeStamp < DATEADD(Day, DATEDIFF(Day, 0, GetDate())-1, 0)

回答by Maslow

you can have your program do it, or set up a sql agent job.

你可以让你的程序来做,或者设置一个sql 代理作业

回答by Darren

You could create a SQL Jobto run each day and execute a specified stored procedure.

您可以创建一个SQL Job每天运行并执行指定的存储过程。

http://technet.microsoft.com/en-us/library/ms190268.aspx

http://technet.microsoft.com/en-us/library/ms190268.aspx