10 December 2009

Check for the existence of a sql temp table

Here's an easy way to check if a temp table exists, before trying to create it (ie. for reusable scripts):

IF object_id('tempdb..#MyTempTable') IS NOT NULL
BEGIN
DROP TABLE #MyTempTable
END

CREATE TABLE #MyTempTable
(
ID int IDENTITY(1,1),
   SomeValue varchar(100)
)
GO

That way, if you have to change databases in the query window, you don't have to drop the tables before you run it again.

Trovato qui.