I want to drop some tables programmatically that may or may not exist. The goal would be a scheduled job. I can make it a manual process by putting it in a SP but I believe in automation when possible. I found this How to drop tables based on sys.objects? but I cant figure out how to make it work. It only deleted one table.
I am using SQL Server 2005.
This is what I tried based on the above mentioned link:
DECLARE @sql NVARCHAR(MAX);
SELECT @sql = N'DROP TABLE '
+ QUOTENAME(SCHEMA_NAME([schema_id]))
+ '.' + QUOTENAME(name) + ';'
FROM sys.tables
WHERE create_date < dateadd(d, -7, getdate()) and [name] like 'tmpTableDump%';
EXEC sp_executesql @sql;
I have never made a scheduled job but I figured I should be able to do it once I get the code right. I am not a DBA but an application programmer.
WBratz provided the solution. Here is the completed answer:
DECLARE @sql NVARCHAR(MAX)
DECLARE @count int
SELECT @count = COUNT(*) from sys.tables where create_date < dateadd(d, -7, getdate()) and [name] like 'tmpTableDump%'
WHILE @COUNT > 0
BEGIN
SELECT @sql = N'DROP TABLE '
+ QUOTENAME(SCHEMA_NAME([schema_id]))
+ '.' + QUOTENAME(name) + ';'
FROM sys.tables
WHERE create_date < dateadd(d, -7, getdate()) and [name] like 'tmpTableDump%'
EXEC sp_executesql @sql;
SET @count = (SELECT (@count - 1))
END