要求查询不时删除数据

时间:2012-01-24 08:08:15

标签: sql sql-server-2008

我在sql 2008中有一个带有40个表的数据库:

在每个表上都有一个DateTime列,范围从

2010-01-01 09:00:00.000至2012-01-23 22:00:00.000

我需要一个查询来删除所有表的数据,时间范围从17:31:00.000到22:00:00.000

结果将与现在相同,但时间范围为09:00:00.000至17:30:00.000

帮我解决这个问题。

非常感谢

1 个答案:

答案 0 :(得分:2)

DELETE FROM YourTable
WHERE CAST(DateTimeColumn AS TIME) BETWEEN '17:31' AND '21:59'

对于所有表格,请使用:

EXEC sp_msforeachtable N'DELETE FROM ? WHERE CAST(DateTimeColumn AS TIME) BETWEEN ''17:31'' AND ''21:59'''

但是我怀疑你的所有桌子都有相同的列8 - )

如果您想检查运行期间出现的错误,请尝试以下操作:

EXEC sp_msforeachtable N'PRINT ''?''; BEGIN TRY DELETE FROM ? WHERE CAST(DateTimeColumn AS TIME) BETWEEN ''17:31'' AND ''21:59''; END TRY BEGIN CATCH PRINT ERROR_MESSAGE() END CATCH'