This query is supposed to be dropping temp tables/views from a sql DB however when dropping the last table/view it keeps looping. Anyone have an answer as why this would be going into an infinite loop when dropping the last table?
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)
DECLARE @type VARCHAR(50)
DECLARE @tmp_table TABLE
(
table_name VARCHAR(50)
, table_type VARCHAR(50)
)
;WITH cte_tempTables
AS (
SELECT
table_name
, crdate
, crdate + 90 [ExperiationDate]
, TABLE_TYPE
FROM
INFORMATION_SCHEMA.TABLES t
inner join sysobjects s
on s.name = t.table_name
WHERE
TABLE_CATALOG = 'SBR_Temp'
AND t.table_name NOT IN ( 'DaleDelq' ,'tblCancelContract' ,
'tblCreateContracts' ,'MWFRTPay' )
)
INSERT INTO
@tmp_table
(
table_name
, table_type
)
select
table_name
, table_type
FROM
[cte_tempTables]
WHERE
ExperiationDate < GETDATE()
SELECT TOP 1
@name = [table_name]
, @type = CASE WHEN [table_type] = 'BASE TABLE' THEN 'TABLE'
ELSE 'VIEW'
END
FROM
@tmp_table
WHILE @name IS NOT NULL
OR @name <> ''
BEGIN
SELECT
@SQL = 'DROP ' + @type + ' SBR_Temp.[dbo].[' + RTRIM(@name) + ']'
--EXEC (@SQL)
PRINT 'Dropped ' + @type + ':' + @name
DELETE
@tmp_table
WHERE
[table_name] = @name
SELECT TOP 1
@name = [table_name]
, @type = CASE WHEN [table_type] = 'BASE TABLE' THEN 'TABLE'
ELSE 'VIEW'
END
FROM
@tmp_table
SELECT @name
END
GO
here is an example of the results
(4 row(s) affected)
Dropped VIEW:vue_SunsetCoveClientInventory
(1 row(s) affected)
(1 row(s) affected)
Dropped VIEW:vue_SunsetCoveClientCoOwners
(1 row(s) affected)
(1 row(s) affected)
Dropped TABLE:BKDischarge
(1 row(s) affected)
(1 row(s) affected)
Dropped VIEW:vue_nocoop
(1 row(s) affected)
(1 row(s) affected)
Dropped VIEW:vue_nocoop
(0 row(s) affected)
(1 row(s) affected)
Dropped VIEW:vue_nocoop
(0 row(s) affected)
(1 row(s) affected)
Dropped VIEW:vue_nocoop
(0 row(s) affected)
(1 row(s) affected)
Dropped VIEW:vue_nocoop
(0 row(s) affected)
(1 row(s) affected)
Dropped VIEW:vue_nocoop
(0 row(s) affected)
Once you have no more rows in
@tmp_table, you are no longer changing the value of@name. I think you’d rather use:Changing to this style of check also has the benefits of:
SELECT TOP 1...in two places.You can run this demo code to see your issue in simplified form: