日期:2014-05-18  浏览次数:20455 次

为何会出错???
这么简单的句子为何会出错?

if   (1=1)
begin
select   *   into   #temp1   from   Table1
end
else
begin
select   *   into   #temp1   from   Table2
end

错误信息:
服务器:   消息   2714,级别   16,状态   1,行   7
数据库中已存在名为   '#temp1 '   的对象。

注:#temp1不可能存在

------解决方案--------------------
临时表只能插入一次,要重新插入必须先释放掉临时表

IF EXISTS (SELECT * FROM tempdb.dbo.sysobjects WHERE id =object_id( 'tempdb.dbo.#temp1 ')) DROP TABLE tempdb.#temp1
------解决方案--------------------
if (1=1)
begin
if object_id( 'tempdb..#temp1 ') is not null
drop table #temp1
select * into #temp1 from Table1
end
else
begin
if object_id( 'tempdb..#temp2 ') is not null
drop table #temp2
select * into #temp1 from Table2
end