使用 SQL Server 查询删除日期早于 30 天的行
我需要一个 SQL 语句来删除超过 30 天的行。
我的表 events
有一个字段 date
,其中包含插入数据库的日期和时间。
这行得通吗?从结果中选择 * WHERE [日期] >= DATEADD(d, -30, getdate())
I need a SQL statement to delete row that are older than 30 days.
My table events
has a field date
that contains the date and the time it was inserted in the database.
Will this work?SELECT * from Results WHERE [Date] >= DATEADD(d, -30, getdate())
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
在 WHERE 子句中使用 DATEADD:
您还可以使用缩写
d
或dd
而不是day
。Use DATEADD in your WHERE clause:
You can also use abbreviation
d
ordd
instead ofday
.你也可以使用
You could also use
尽管 DATEADD 可能是最透明的方式,但值得注意
只需
getdate()-30
就足够了。另外,您是否要查找从现在起 30 天后的时间,即包括小时、分钟、秒等?或从今天午夜起 30 天(例如 12/06/2010 00:00:00.000)。在这种情况下,您可以考虑:
Although the
DATEADD
is probably the most transparrent way of doing this, it is worth notingthat simply
getdate()-30
will also suffice.Also, are you looking for 30 days from now, i.e. including hours, minutes, seconds, etc? Or 30 days from midnight today (e.g. 12/06/2010 00:00:00.000). In which case, you might consider:
要从表中删除 Date_column 中的日期时间值早于 30 天的记录,请使用以下查询:
...或者:
要从表中删除 Date_column 中的日期时间值早于 12 小时的记录:
要从Date_column 中的日期时间值早于 15 分钟的表:
来自:http://zarez.net/?p=第542章
To delete records from a table that have a datetime value in Date_column older than 30 days use this query:
...or this:
To delete records from a table that have a datetime value in Date_column older than 12 hours:
To delete records from a table that have a datetime value in Date_column older than 15 minutes:
From: http://zarez.net/?p=542
GETDATE()
对我使用 mySQL 8 不起作用但存在:
GETDATE()
didn't work for me using mySQL 8but this does:
您还可以设置两个日期之间:
You could also set between two dates:
我们可以使用这个:
但更好的选择是使用:
前者是不可控制的(即函数位于表达式的右侧,因此不能使用索引)并且需要 30 秒,后者是可控制的并且需要不到 10 秒的时间。第二。
We can use this:
But a better option is to use:
The former is not sargable (i.e. functions on the right side of the expression so it can’t use index) and takes 30 seconds, the latter is sargable and takes less than a second.
我更喜欢将其保留为日期时间字段并使其仅是日期(没有时间),而不是转换为 varchar 以仅获取日期(convert(varchar(8), [Date], 112)) )。
Instead of converting to varchar to get just the day (convert(varchar(8), [Date], 112)), I prefer keeping it a datetime field and making it only the date (without the time).
删除超过 30 天的行。
Delete row older than 30 days.