SQL Server: Create and drop a temporary table

The following shows a basic example of how to create a temporary table, insert some data and select the data out:
CREATE TABLE #TEMPTBL
(IsSomething BIT,
IntValue BIGINT)

INSERT INTO #TEMPTBL (IsSomething, IntValue) VALUES (1, 1234)

SELECT * FROM #TEMPTBL

When scripting with temporary tables it’s more difficult to figure out if the table exists or not (i.e. you can’t use the normal mechanism), so I simply wrap the drop table command in a try catch block and ignore any errors:

BEGIN TRY
DROP TABLE #TEMPTBL
END TRY
BEGIN CATCH
END CATCH

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s