当前位置: 代码迷 >> Sql Server >> if else 同一個臨時表 怎么處理
  详细解决方案

if else 同一個臨時表 怎么處理

热度:397   发布时间:2016-04-24 09:23:18.0
if else 同一個臨時表 如何處理
本帖最后由 qinai0752 于 2015-01-23 10:46:27 编辑
if 1>2
begin 
select 1 into #temp01
end
else
begin  
IF Object_id('tempdb..#temp01') IS NOT NULL DROP TABLE temp01
select 2 into #temp01
end 


Msg 2714, Level 16, State 1, Line 9
There is already an object named '#temp01' in the database.


怎麼解決這種問題的 ,是要同一個臨時表插入數據啊 ! if  和else 不是分開的麼
------解决思路----------------------
create table #test
(
.......
)
if
insert #test
else
insert #test
------解决思路----------------------
先创建表,然后用insert into #tmp select ……
------解决思路----------------------
if 1>2
begin
IF Object_id('tempdb..#temp01') IS NOT NULL DROP TABLE #temp01
select 1 into #temp01
end
else
begin  
IF Object_id('tempdb..#temp01') IS NOT NULL DROP TABLE #temp01
select 2 into #temp01
end 

------解决思路----------------------
按照你的逻辑运行是可能没有问题,问题在SQL编译的时候却认为临时表已经存在,即一次会话中只能SELECT INTO 一次的方式建立临时表
你可以用普通表替代,使用完主动删除
  相关解决方案