I want to create a Stored procedure and Job in Ms SQL server that would delete all tables in a schema that are more than a weeks old.
i create backups every single day and i want to automate the process by scheduling a job to delete any backups(SQL Tables) that are older than a week.
Your help would be greatly appreciated.
You can use the sys.objects
keyword within SQL Server to accomplish this.
The query would be something like:
USE [Your_Database_Name];
GO
SELECT name AS object_name
,SCHEMA_NAME(schema_id) AS schema_name
,type_desc
,create_date
,modify_date
FROM sys.objects
WHERE create_date > GETDATE() - [No_Of_Days_Old]
ORDER BY create_date;
GO
This above example is a slight variation on the first example shown on the MSDN page that details the sys.objects
keyword (A. Returning all the objects that have been modified in the last N days).
That page can be found here:
sys.objects (Transact-SQL)
and is a great resource for many different methods of querying the "metadata" of your database objects.
Of course, the above will simply "SELECT" the table name that will need to be deleted and won't actually delete (or DROP) the table from your database.
To achieve this, you will need a mechanism to issue a DROP TABLE
command. Unfortunately, the DROP TABLE
command won't accept a parameter valued table name (i.e. You can't do DROP TABLE @tablename
), but you can build a string/varchar of a complete T-SQL statement and EXECUTE
it).
To achieve this, you can use a CURSOR to loop through the results of the earlier SELECT
statement, building a new T-SQL command in a string/varchar that will drop the table name. An example of this is below:
DECLARE @tname VARCHAR(100)
DECLARE @sql VARCHAR(max)
DECLARE db_cursor CURSOR FOR
SELECT name AS tname
FROM sys.objects
WHERE create_date > GETDATE() - 7
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @tname
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql = 'DROP TABLE ' + @tname
--EXEC (@sql)
PRINT @sql
FETCH NEXT FROM db_cursor INTO @tname
END
CLOSE db_cursor
DEALLOCATE db_cursor
Note that in the above example, I have commented out the line EXEC (@sql)
. This is the line that actually executes the T-SQL statement in the @sql variable, and since it's a destructive command, I simply commented it out and used a PRINT @sql
command instead (the line below). Run this as is, to see what tables you're likely to delete, and when you're happy, uncomment the EXEC (@sql)
command and comment out the PRINT @sql
command!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With