1個のクエリ内で drop create で一時テーブル使い回ししたいなーと書いてたらエラーになったのでメモ。
こういうのがエラーになってクエリ自体実行されない。
drop table if exists #temptable select [Name] into #temptable from sys.tables select * from #temptable drop table if exists #temptable /* ↑で drop table してるのでクエリ実行時にエラー */ select * from #temptable /* error Msg 208, Level 16, State 0 Invalid object name '#temptable'. */ /* ↑で drop table してても、こいつがあるとクエリの実行がされない!*/ select [Name] into #temptable from sys.tables /* error Msg 2714 Msg 2714, Level 16, State 1 There is already an object named '#temptable' in the database. */
正解は2回目以降は truncate + insert select。
drop table if exists #temptable select [Name] into #temptable from sys.tables select * from #temptable truncate table #temptable select * from #temptable insert into #temptable select [Name] into #temptable from sys.tables