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.objectskeyword within SQL Server to accomplish this.The query would be something like:
This above example is a slight variation on the first example shown on the MSDN page that details the
sys.objectskeyword (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 TABLEcommand. Unfortunately, theDROP TABLEcommand won’t accept a parameter valued table name (i.e. You can’t doDROP TABLE @tablename), but you can build a string/varchar of a complete T-SQL statement andEXECUTEit).To achieve this, you can use a CURSOR to loop through the results of the earlier
SELECTstatement, building a new T-SQL command in a string/varchar that will drop the table name. An example of this is below: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 aPRINT @sqlcommand instead (the line below). Run this as is, to see what tables you’re likely to delete, and when you’re happy, uncomment theEXEC (@sql)command and comment out thePRINT @sqlcommand!