I am trying the following query
if exists (select 1 from emp where eid = 6)
begin
if object_id('tempdb..#columntable') is not null
begin
drop table #columntable
end
create table #columntable (oldcolumns varchar(100))
end
else
begin
if object_id('tempdb..#columntable') is not null
begin
drop table #columntable
end
create table #columntable (newcolumns varchar(100))
end
But I am getting the error
Msg 2714, Level 16, State 1, Line 8
There is already an object named '#columntable' in the database.
Can anyone suggest why? The same query works fine if I do not write the else part.
The error is wrong, remove the if clause and it runs through fine. Thus the problem is in the exists:
Use global temp tables and wrap the select in exec.
Example:
Fail
Win
This will fool the buggy parser that is trying to be smarter than it is. And Microsoft - please fix this.
This is a SQL Server parser error unfortunately (confirmed by Microsoft).
@DizGrizz is also right -
SELECT .. INTO #SomeTable
doesn't work if repeated inIF .. ELSE
statements.IF .. ELSE .. CREATE TABLE #SomeTempTable
In answer to the actual question, creating then altering the table works (you also only have to check and drop once)...
IF .. ELSE .. SELECT INTO #SomeTempTable
The issue I had however was the same as @DizGrizz:
IF .. ELSE
combined withSELECT .. INTO #SomeTable
fails. As a workaround it's possible to select the top 0 rows (i.e. none) to create the table with the correct column types. (This insulates the script from column type changes and also avoids the pain of declaring every type.)INSERT INTO
can then be used, providedIDENTITY_INSERT
is set toON
to prevent errors:Temp tables are not dropped automatically at the end of a query, only when the current connection to the DB is dropped or you explicitly delete them with
DROP TABLE #columntable
Either test for the existence of the table at the start of the query or alwayas delete it at the end (preferably both)
EDIT: As Matrin said in his comment, this is actually a parse error. You get the same error if you only parse the SQL as when you execute it.
To test that out I split up your query and tried:
The parser is happy with that. Interestingly if you change to using non-temp tables the original query parses fine (I realise the problems that would create, I was just interested to find out why the query would not parse).
You can check if it exists by doing:
Well I got the answer... As Martin said this is a parse/compile issue. So I Tried changing my script as below
And this worked for me.