线上SQLSERVER服务器有些表有每天备份一次,日子久了,旧的表数据已没有用了,旧的表并没有清理,如果一张一张删除,鼠标都要坏几个,哈哈,
基于这个原因,写了一个清理的脚本,自己线上环境使用的脚本,有需要的同学,可以参考一下哈。。。
表清单:
以上表保留近30天,超过30天的表,可以直接删除
以下脚本可以实现上面的功能:
use nsudes
if object_id(N'tmp_date',N'U') is not null
DROP TABLE tmp_date
if object_id(N'tmp_table_name',N'U') is not null
DROP TABLE tmp_table_name
SELECT table_name,SUBSTRING(table_name,20,8) as date
into tmp_date
FROM INFORMATION_SCHEMA.TABLES where table_name like 'EgStock_StockSpace_%'
select table_name into tmp_table_name from tmp_date where table_name not in ('tmp_date') and date <convert(varchar(10),DATEADD(DAY,-30,getdate()),120)
declare @sql1 varchar(max)
declare @sql2 varchar(max)
DECLARE @tablename varchar(100)
DECLARE My_Cursor CURSOR
FOR (SELECT table_name FROM tmp_table_name)
OPEN My_Cursor;
FETCH NEXT FROM My_Cursor INTO @tablename;
WHILE @@FETCH_STATUS = 0
BEGIN
set @sql1 = ' truncate table '+@tablename+' '
exec(@sql1)
print ' truncate table '+@tablename+' '
set @sql2 = ' drop table '+@tablename+' '
exec(@sql2)
print ' drop table '+@tablename+' '
waitfor delay '00:00:01'
FETCH NEXT FROM My_Cursor INTO @tablename;
END
CLOSE My_Cursor;
DEALLOCATE My_Cursor;
GO