1、定义表:Table_To_Purge [Table_Name,Day_Latency,Date_Field_Name]
用于存储需要删除的表的信息,表名、删除时间、字段名
2、设置一个job定期执行存储过程:EXECUTE [TISC].[dbo].[PURGE_TABLES]
3、编写存储过程:
CREATE PROCEDURE DBO.PURGE_TABLES AS
DECLARE
@tablename AS varchar(64),
@daylatency AS int,
@datefieldname AS varchar(64),
@sqldelete AS varchar(512),
@eldest AS int
BEGIN
DECLARE TABLE_CURSOR CURSOR FOR
SELECT TABLE_NAME, DAY_LATENCY, DATE_FIELD_NAME FROM TABLE_TO_PURGE
BEGIN
SET @eldest = 0
OPEN TABLE_CURSOR
FETCH NEXT FROM TABLE_CURSOR INTO @tablename, @daylatency, @datefieldname
WHILE (@@FETCH_STATUS = 0)
BEGIN
IF ((@datefieldname = 'PIECE_ID') OR (@datefieldname = 'PLATEID') OR (@datefieldname = 'PLATE_ID'))
BEGIN
SET @sqldelete = 'delete FROM ' + @tablename +
' WHERE ' + @datefieldname + ' IN (SELECT PIECE_ID FROM PIECE_PRODUCTION WHERE DISCHARGING_TIME < (GETDATE() - ' +
CAST(@daylatency AS varchar(3)) + '))'
END
ELSE
BEGIN
SET @sqldelete = 'delete FROM ' + @tablename + ' WHERE ' + @datefieldname +
' < (GETDATE() - ' + CAST(@daylatency AS varchar(3)) + ')'
END
PRINT @sqldelete
EXECUTE (@sqldelete)
PRINT CAST(@@ROWCOUNT AS varchar(5))
IF (@eldest < @daylatency)
BEGIN
SET @eldest = @daylatency
END
FETCH NEXT FROM TABLE_CURSOR INTO @tablename, @daylatency, @datefieldname
END
CLOSE TABLE_CURSOR
DEALLOCATE TABLE_CURSOR
DELETE FROM PIECE_PRODUCTION WHERE DISCHARGING_TIME < (GETDATE() - @eldest)
DELETE FROM MILL_PDI WHERE CREATION_TIME < (GETDATE() -20)
END
END
GO