2016-06-29 6 views
0

次のコードがあります。リサイクル時のテーブル名

If OBJECT_ID('tempdb.dbo.#tempTable', 'U') is not null 
drop table #tempTable; 

select 'bacon' into #tempTable 
select * from #tempTable 

If OBJECT_ID('tempdb.dbo.#tempTable', 'U') is not null 
drop table #tempTable; 

select 'sandwich' into #tempTable 
select * from #tempTable 
  1. それがselect into文でそれを読み込む/作成
  2. が存在する場合は、一時テーブルをドロップする声明
  3. に選択して、それを移入/作成
  4. が存在する場合は、一時テーブルをドロップ

これは私が書いたコードを読む方法ですが、SSMSはエラーメッセージが表示されるために違った方法で読むと思います。

メッセージ2714、レベル16、状態1、行11 という名前のオブジェクトが既にデータベースにあります。

If Object_IDの部分がコードの先頭に実行される可能性があります。テーブルは2番目のドロップテーブルステートメントでドロップされません。もちろん、別の一時表を使用することもできますが、この例が機能しない理由を理解したいと思います。

+1

各文の後に、または少なくとも2番目の 'DROP TABLE'の後にキーワードGOを追加してください。 – BJones

+1

@bjonesは私が必要としたものです。それを答えとして書くと、正しいとマークします。ありがとうございました! – Observer

答えて

1

私は、バッチの一部としてテンポラリテーブルがまだあると考えています。

If OBJECT_ID('tempdb.dbo.#tempTable', 'U') is not null 
drop table #tempTable; 

select 'bacon' into #tempTable 
select * from #tempTable 

If OBJECT_ID('tempdb.dbo.#tempTable', 'U') is not null 
drop table #tempTable; 

GO --At least this should do the trick 

select 'sandwich' into #tempTable 
select * from #tempTable 

Microsoftは"DROP TABLE and CREATE TABLE should not be executed on the same table in the same batch. Otherwise an unexpected error may occur."

を示唆しているが、あなたは、もはや存在しませんGO変数の後に、変数とストアドプロシージャでこれを使用している場合にも、注意してください。

関連する問題