Greetings,
I've got a procedure, as follows, which is used to archive tables when after 13 months. We keep a table for each month of the year, and after 13 months, I no longer require the data to be online. Tables are named LogsYYYY_MM example: Logs2009_10 (for October, 2009).
Since I typically try to use set based logic instead of cursors, can someone please point me in the right direction with this? (Also, the backup fails in this example, indicating that the cursor is already open. Not sure why it's doing that, but the point is to try to do this without cursors, so I'm not worrying about the error at this point ...)
ALTER PROCEDURE archiveLogs AS BEGIN SET NOCOUNT ON;
DECLARE
@lastMonthToKeep varchar(15),
@tempMonth varchar(2),
@tempYear varchar(4),
@archiveTable varchar(50),
@sql varchar(2000),
@sqlStmt nvarchar(2000),
@backupFilename varchar(200)
SET @tempMonth = (SELECT datePart(MM,dateAdd(MM,-13,getDate())))
IF (LEN(@tempMonth) < 2)
SET @tempMonth = '0' + @tempMonth
SET @tempYear = (SELECT datePart(YYYY,dateAdd(MM,-13,getDate())))
-- we will remove all logs tables that are < tempMonth and tempYear
SET @lastMonthToKeep = 'Logs' + @tempYear + '_' + @tempMonth
-- CURSOR to select all the tables that must be archived (typically will only be one table, unless the proc has stopped running for a while)
DECLARE tablesToArchiveCur CURSOR FOR
SELECT name FROM sysobjects
WHERE xtype = 'u' AND LEN(name) = 11 AND LEFT(name,4) = 'Logs' AND SUBSTRING(name,9,1) = '_' AND name < @lastMonthToKeep
ORDER BY name
OPEN tablesToArchiveCur
FETCH NEXT FROM tablesToArchiveCur INTO @archiveTable
WHILE (@@FETCH_STATUS = 0)
BEGIN
-- copy data from Logs.dbo.archiveTable into archiveLogs.dbo.archiveTable
SET @sql = 'SELECT * INTO archiveLogs.dbo.' + @archiveTable + ' FROM ' + @archiveTable
EXEC(@sql)
SET @backupFilename = 'D:\DB Backups\LIVE_BACKEND_archiveLogs_' + @archiveTable + '.bak'
BACKUP DATABASE archiveLogs TO DISK = @backupFilename WITH NOFORMAT, INIT, SKIP, NOREWIND, NOUNLOAD, STATS = 10
SET @sql = 'DROP TABLE archiveLogs.dbo.' + @archiveTable
EXEC(@sql)
-- drop existing table
SET @sql = 'DROP TABLE logs.dbo.' + @archiveTable
EXEC(@sql)
FETCH NEXT FROM tablesToArchiveCur INTO @archiveTable
END
CLOSE tablesToArchiveCur
DEALLOCATE tablesToArchiveCur
END
GO
I've removed some logging and try/catch logic in an attempt to keep this small and simple.
Any suggestions?
Thanks!
Bill