Please, can someone suggest how I can drop the tables that are in a SQL table as values? As per the example, I would like to drop them if they are expired.
https://i.stack.imgur.com/POhfV.png
Thanks in advance!
Please, can someone suggest how I can drop the tables that are in a SQL table as values? As per the example, I would like to drop them if they are expired.
https://i.stack.imgur.com/POhfV.png
Thanks in advance!
Here is another way to do this, if you don't want to use a cursor:
DECLARE @Run INT,
@SQL VARCHAR(500)
CREATE TABLE #TableList
(
TableID INT IDENTITY(1,1),
TableCMD VARCHAR(500)
);
INSERT INTO #TableList (TableCMD)
SELECT 'DROP TABLE ' + tablename
FROM YourTable
WHERE ExpiryDate < GETDATE();
SET @Run = (SELECT MAX(TableID)
FROM #TableList)
WHILE @Run > 0
BEGIN
SELECT @SQL = ( SELECT TableCMD
FROM #TableList
WHERE TableID = @Run)
EXEC (@SQL)
SET @Run = @Run - 1
END
You should probably also delete the records of expired tables from your main table, so you don't get failures next time when you attempt to drop tables that don't exist. Or better yet, add a status column to mark them as deleted, but keep the records for reference.
Like this with a cursor and dynamic queries: Drop all tables whose names begin with a certain string
DECLARE @tname varchar(100)
DECLARE table_cursor CURSOR FOR
SELECT TableName FROM TableCatalog WHERE GETDATE() > ExpiryDate
OPEN cursor
FETCH NEXT FROM table_cursor INTO @tname
WHILE @@fetch_status = 0
BEGIN
EXECUTE sp_executesql 'DROP TABLE ' + @tname
FETCH NEXT FROM table_cursor INTO @tname
END
CLOSE table_cursor;
DEALLOCATE table_cursor