I have a query where I insert some values from a table:
SELECT ID, NAME INTO #tmpTable1 FROM TableOriginal
First execution is fine, if I press F5(Run) in MSSMS (Microsoft Sql Server Management Studio), the error occured:
Msg 2714, Level 16, State 6, Line 4
There is already an object named '#tmpTable1' in the database.
Good. I decided to check before insert data from TableOriginal
to #tmpTable1
using:
IF OBJECT_ID('tempdb.#tmpTable1') IS NOT NULL DROP TABLE #tmpTable1
Not working, the error shows again as above.
I saw in tempdb
database the following temporary table name:
dbo.#tmpTable1__________________0000007
Why? Every time when create a temporary table (using first query), the table name will be generated automatically in MSSMS ?
How to remove the existing temporary table to do a new table with new values ?
Consider using the following pattern: BEGIN TRANSACTION; CREATE TABLE #Results; ...; DROP TABLE #Results; COMMIT . If the transaction succeeds, the table will be removed. If it fails, the table will be gone as well (since it was created within the transaction). In any case: No need to check if the table already exists.
Temporary tables are stored inside the Temporary Folder of tempdb. Whenever we create a temporary table, it goes to the Temporary folder of the tempdb database.
Local SQL Server temp tables are created using the pound symbol or “hashtag” followed by the table name. For example: #Table_name.
You're darn close - you need to use two dots in your check:
IF OBJECT_ID('tempdb..#tmpTable1') IS NOT NULL ** | use two dots here!
Basically, this is saying: check in the tempDB
and I don't care what schema the table is in
As Joe rightfully said: this is not 100% correct: it doesn't check in every schema - it will only check in the default owner's schema - normally dbo
. So this would work, too:
IF OBJECT_ID('tempdb.dbo.#tmpTable1') IS NOT NULL
If you happen to create your objects in a schema other than the default owner's, then you'll need to explicitly specify the schema you're referring to. But the temp tables in tempDB
are indeed creating in the dbo
schema.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With