SQL Server 'ignores' drop table command [duplicate]
-
30-09-2020 - |
문제
I have a 500+ lines stored proccedure which I am writting and testing using the Microsoft SQL Management studio. Today I encounter the following 'strange' case. My query (in pseudocode) look like the following
create table #TempTable1 (Name varchar(30))
-- Some queries involving #TempTable1
drop table #TempTable1
-- Some queries
declare MyCursor cursor fast_forward for
select ......
open MyCursor
fetch next from MyCursor into @CursorValue
while @@fetch_status = 0
begin
create table #TempTable1 (Name varchar(30))
-- Some queries involving #TempTable1
drop table #TempTable1
fetch next from MyCursor into @CursorValue
end
close MyCursor
deallocate MyCursor
My query fails with an error in the second create table
There is already an object named '#TempTable1' in the database.
I know that due to query optimizations the commands are not running in the sequence I am typing them. However this error still seems strange to me. I can put some go
commands to force the execution, but this will create some other problems in my code e.g. I will have to redeclare some variables e.t.c. Renaming the tables will solve the problem but it will harm a little the readabillity of the code. So it is more 'curiocity' than an 'actual problem'.
Any suggestions on why this is happening and how I can avoid it?
해결책
You can see you are creating temptable with same name.You cannot create temp table with same name in single query or batch this is documented as per BOL document. From Bol document
If more than one temporary table is created inside a single stored procedure or batch, they must have different names.
You should use below logic it will just check before creating and deleting
IF OBJECT_ID('tempdb..#Temptable1') IS NOT NULL
DROP TABLE #Temptable1
CREATE TABLE #Temptable1(name nvarchar(30))
Which would make your query like
IF OBJECT_ID('tempdb..#Temptable1') IS NOT NULL
DROP TABLE #Temptable1
CREATE TABLE #Temptable1(name nvarchar(30))
-- Some queries involving #TempTable1
IF OBJECT_ID('tempdb..#Temptable1') IS NOT NULL
DROP TABLE #Temptable1
-- Some queries
declare MyCursor cursor fast_forward for
select ......
open MyCursor
fetch next from MyCursor into @CursorValue
while @@fetch_status = 0
begin
IF OBJECT_ID('tempdb..#Temptable2') IS NOT NULL--new temp table
DROP TABLE #Temptable2
CREATE TABLE #Temptable1(name nvarchar(30))
-- Some queries involving #TempTable1
IF OBJECT_ID('tempdb..#Temptable2') IS NOT NULL
DROP TABLE #Temptable2
fetch next from MyCursor into @CursorValue
end
close MyCursor
deallocate MyCursor