SQL Server IF文内、一時テーブルへのINSERT INTOで メッセージ 2714 | WEBエンジニア社長のブログ

SQL Server IF文内、一時テーブルへのINSERT INTOで メッセージ 2714

SQL Serverで、IF~ELSE内で、同名の一時テーブルへのINSERT INTOを実行しようとすると下記エラーメッセージが表示され、ストアドプロシージャを作成できない場合の対処方法。


サーバー : メッセージ 2714、レベル 16、状態 1、プロシージャ xxxx、行 62
データベースにオブジェクト名 '#temp1' が既に存在します。



[例1]


If @type = 'A'
select * into #temp1 from orders where type='A"
Else if @type = 'B'
select * into #temp1 from orders where type='B"



[例2]


If @type = 'A'
create table #temp1 (type int)
Else if @type = 'B'
create table #temp1 (type varchar(10))




【解決策】
一時テーブルなどのオブジェクトの作成は、IF文の前に行います。

[例1の場合]


create table #temp1 (type int, date datetime)

If @type = 'A'
insert into #temp1 select * from orders where type='A"
Else if @type = 'B'
insert into #temp1 select * from orders where type='B"



[例2の場合]


create table #temp1 (type int)

If @type = 'A'
alter table #temp1 alter column type int
Else if @type = 'B'
alter table #temp1 alter column type varchar(10)