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

存储过程中if的用法
要根据不同的输入参数,来执行不同的语句,执行一个生成临时表的查询

我用if来判断输入参数,然后分别执行不同的语句,但是保存存储过程时,提示那个临时表已经存在,看来这个sqlserver语法检查还是不太完善啊。。。从逻辑上看,在实际执行的时候,是不会出现这种情况的

各位大大,帮我出个招吧

if   @jfdw= '所有单位 '
begin
Select   [栋号]   =   dbo.GetDongHao([地址]),[产权单位],
[用电量]   =   Sum([用电量]),
[住户数]   =   Count(地址),
[楼交电费]   =   Sum([交电费]+[交地下电费])
Into   #楼栋单位用量汇总
From   [sndf_wy]
Where   [季度]   =   @quarter
Group   By   dbo.GetDongHao([地址]),产权单位;
end
else
begin
Select   [栋号]   =   dbo.GetDongHao([地址]),[产权单位],
[用电量]   =   Sum([用电量]),
[住户数]   =   Count(地址),
[楼交电费]   =   Sum([交电费]+[交地下电费])
Into   #楼栋单位用量汇总
From   [sndf_wy]
Where   [季度]   =   @quarter   and   产权单位   in   (@jfdw)
Group   By   dbo.GetDongHao([地址]),产权单位;
end

------解决方案--------------------
--呵呵,两个if里的临时表别同名
--如果你是以#+名称作为数据表名称,如 #aReport
if exists(select 1 from tempdb..sysobjects where name like '#aReport[___________] ')
drop table #aReport
-------------------------------
create table t(id int)
insert into T select 1
insert into T select 2
insert into T select 3

declare @jfdw int
set @jfdw = 2
if @jfdw=1
begin
if exists(select 1 from tempdb..sysobjects where name = '## ')
drop table ##
Select * Into ## From @t
end
else
begin
if exists(select 1 from tempdb..sysobjects where name = '### ')
drop table ###
Select * Into ### From @t
end

--drop table t
------解决方案--------------------
看了一下,你这种情况最好在IF ELSE 之前先创建临时表,下面的判断中直接INSERT