So for example the following statements will run without error:
- create table #mytable(col1 int)
- insert into #mytable values(2)
- delete from #mytable
- drop table #mytable
if OBJECT_ID('#mytable') is not null drop table #mytable
create table #mytable(col1 varchar(10))
It runs without error but if you try running it again you will get the following error:
Msg 2714, Level 16, State 6, Line 2
There is already an object named '#mytable' in the database.
So the check for the temporary table has not done what we expected and the table wasn't dropped. You need to add a reference to the tempdb in the statement for it to work:
if OBJECT_ID('tempdb..#mytable') is not null drop table #mytable
create table #mytable(col1 varchar(10))
The statement now runs successfully. If however you were to add the database reference to both occurances of the table like so:
if OBJECT_ID('tempdb..#mytable') is not null drop table tempdb..#mytable
create table #mytable(col1 varchar(10))
Then this will produce the following error:
Database name 'tempdb' ignored, referencing object in tempdb.
You do not need to put the reference into the drop table part of the statement.
No comments:
Post a Comment