答案 0 :(得分:1)
如果您不想使用游标,这是另一种方法:
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
您还应该从主表中删除过期表的记录,这样下次尝试删除不存在的表时就不会出现故障。或者更好的是,添加状态列以将其标记为已删除,但保留记录以供参考。
答案 1 :(得分:0)
与光标和动态查询一样: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