How to check if a temp table exists before dropping it in SQL Server?

I’m working on some T-SQL scripts that need to run multiple times. These scripts create temporary tables to hold data during processing. The problem is that when I run the script again, I want to clean up any existing temp tables first before creating new ones.

I need a reliable method to check whether a temporary table already exists in the database before attempting to drop it. This way I can avoid errors when the table doesn’t exist yet.

What’s the most efficient approach to detect if a temp table is present in SQL Server? I’m looking for something that works well in scripts that get executed repeatedly.

also, u can try IF OBJECT_ID('tempdb..#yourTableName') IS NOT NULL DROP TABLE #yourTableName. this works in older versions too, just ensure ur referencing the temp table right!

What about DROP TABLE IF EXISTS #yourTableName? Works in SQL Server 2016+ and it’s cleaner than checking object_id first. Do you need backwards compatibility with older versions sophia39? This syntax is way more readable but I’m curious about performance differences compared to the other approach.

OBJECT_ID works great, but I’d be more explicit about the database context. I always use IF OBJECT_ID('tempdb.dbo.#yourTableName', 'U') IS NOT NULL DROP TABLE #yourTableName in complex stored procedures. The ‘U’ parameter specifically checks for user tables - adds extra validation. I’ve used this across SQL Server 2008 to current versions without issues. The tempdb reference makes sure you’re checking where temp tables actually live, and the explicit schema prevents confusion in multi-schema setups.