MSSQL is terrible for lacking some seemingly straightforward functionality- like the ability to drop a table only if it exists and has no rows. Salt to taste:
-- TODO: accept an array of tables, check all of them for existence and zero rows, then perform drop CREATE PROCEDURE DropTableIfEmpty(@t as nvarchar(max)) AS BEGIN SELECT @t = QUOTENAME(@t) DECLARE @q NVARCHAR(max) IF OBJECT_ID(@t, 'U') IS NOT NULL AND EXISTS( SELECT DISTINCT row_count FROM sys.dm_db_partition_stats WHERE Object_Name(Object_Id) = @t AND row_count = 0 ) BEGIN SELECT @q= N'DROP TABLE' + @t EXEC sp_executesql @q END END
To use: EXEC DropTableIfEmpty 'yourTableName'