向存储过程中添加第二条if else语句

时间:2019-07-11 07:09:56

标签: sql-server

我有一个如下所示的存储过程,可以正常工作。

declare db_cursor cursor for
select Atmosphere, Region, PreATR
from myTbl

open db_cursor
fetch next from db_cursor into @Atmosphere, @Region, @PreATR


while @@FETCH_STATUS = 0
begin

   if @PreATR = 1
      set @q = 'insert into tblA ... '       
   else
      set @q = 'insert into tblB ...
   end

   exec(@q)

   fetch next from db_cursor into @Atmosphere, @Region, @PreATR
end

close db_cursor
deallocate db_cursor

但是现在我需要调整它。所以我想添加另一个if else语句,如下所示。当我这样做时,尽管下面的行突出显示了

  

关闭db_cursor

     

'close'附近的语法不正确。期待会话

    open db_cursor
fetch next from db_cursor into @Atmosphere, @Region, @PreATR


while @@FETCH_STATUS = 0
begin

   if @Region = 55
      set @someVar = 1
   else
      set @someVar = 1
   end

   if @PreATR = 1
      set @q = 'insert into tblA ... '       
   else
      set @q = 'insert into tblB ...
   end

   exec(@q)

   fetch next from db_cursor into @Atmosphere, @Region, @PreATR
end

close db_cursor
deallocate db_cursor

为什么添加这个额外的if else语句会导致这种现象?

2 个答案:

答案 0 :(得分:1)

您收到错误消息是因为,如果其他语法不正确,并且第二个insert语句中也缺少单引号,请尝试按以下更新的查询进行操作,我删除了else语句后的结尾,并在第二个insert语句中添加了单引号-

open db_cursor
fetch next from db_cursor into @Atmosphere, @Region, @PreATR


while @@FETCH_STATUS = 0
begin

   if @Region = 55
      set @someVar = 1
   else
      set @someVar = 1


   if @PreATR = 1
      set @q = 'insert into tblA ... '       
   else
      set @q = 'insert into tblB ...'


   exec(@q)

   fetch next from db_cursor into @Atmosphere, @Region, @PreATR
end

close db_cursor
deallocate db_cursor

注意:每当有多个带有if和else块的语句时,您必须使用如下所示的begin和end-

IF @Var = 1
BEGIN
    PRINT '1';
END
ELSE
BEGIN
    PRINT 'not 1';
END

答案 1 :(得分:1)

我敢肯定,没有光标,您可以做得更简单,更快。不幸的是,问题中没有足够的细节来写出可以帮助您入门的示例

可能您需要这样的东西

insert into tblA (your fields here)
select t.Atmosphere, t.Region, t.PreATR
from   myTbl t
where  t.PreATR = 1
and    more conditions here...

insert into tblB (your fields here)
select t.Atmosphere, t.Region, t.PreATR
from   myTbl t
where  t.PreATR <> 1
and    more conditions here...