当前位置: 代码迷 >> Sql Server >> 怎样设置sql自动删除逐月生成的过期数据表,该怎么解决
  详细解决方案

怎样设置sql自动删除逐月生成的过期数据表,该怎么解决

热度:37   发布时间:2016-04-27 14:15:31.0
怎样设置sql自动删除逐月生成的过期数据表
sql每个月生成一张表,表名相似按年月命名。怎样设置自动删掉三个月以外的表?好像要建立一个作业或建一个触发器解决,求方法

------解决方案--------------------
用定时作业 用getdate()取年月与表名匹配进行删除
------解决方案--------------------
建立JOB了。

delete from tb where datediff(mm,date,getdate()) > 3
------解决方案--------------------
额。看错了,以为是一个表的数据。

表名的命名有规律没,例如按年月命名的表是 YMD201201 YMD201202 这样子,但其他表不会以YMD开头,如果是这样可以采用动态去拼接SQL的删除语句进行删除表。
------解决方案--------------------
探讨
主要是怎样提取表名进行删除?

------解决方案--------------------
Job内容大概如下,给你伪代码.
SQL code
declare @sql varchar(6000)-- sql每个月生成一张表,表名相似按年月命名set @sql='create table tab'+convert(varchar(6),getdate(),112)+' ([表字段列表])'exec(@sql)-- 设置自动删掉三个月以外的表while(exists(select 1 from sysobjects              where xtype='U' and name like 'tab%'             and datediff(m,right(name,6)+'01',getdate())>=3))begin   select @sql='drop table ['+name+'] '      from sysobjects      where xtype='U' and name like 'tab%'     and datediff(m,right(name,6)+'01',getdate())>=3      exec(@sql)   end
------解决方案--------------------
探讨
我有一个想法不知可不可以,就是每张表都有其创建日期,可否根据这个创建时间与表名的相似点进行删除?谢谢各位帮助,尽快结贴
  相关解决方案