如何在sybase ase中做嵌套游标

时间:2019-07-11 07:36:27

标签: sybase sybase-ase

我可以问一下如何在sybase中正确地嵌套一个游标吗? 我的代码下面出现两个错误。

  1. 必须声明变量@notes
  2. 声明游标必须是查询批处理中的唯一语句。

当前的编码尝试:

DECLARE c3 cursor FOR
select distinct cust_ac_no from tempdb..M3_SHP_ACCOUNT_NOTES
where cust_ac_no in ('851243048')
--,'851261620
--order by cust_ac_no, inst_seq_no, ord_no, ref_no, acv_no
GO

DECLARE 
@exec_str1 varchar(8000),
@exec_str2 varchar(8000),
@cust_ac_no varchar(10),
@c_ac varchar(10),
@notes varchar(4000),
@notes2 varchar(8000)

--select @exec_str1 = "select distinct notes from tempdb..M3_SHP_ACCOUNT_NOTES where cust_ac_no = "

OPEN c3
FETCH c3 into @cust_ac_no

WHILE @@sqlstatus = 0

  BEGIN

  DECLARE c2 cursor FOR
  select distinct notes from tempdb..M3_SHP_ACCOUNT_NOTES
  where cust_ac_no = + "'" + @cust_ac_no + "'"
  order by cust_ac_no, inst_seq_no, ord_no, ref_no, acv_no
  GO


  OPEN c2
  FETCH c2 into @notes

  WHILE @@sqlstatus = 0
  BEGIN

  print @notes

  FETCH c2 into @notes  
  END
  CLOSE c2
  DEALLOCATE c2

  print @cust_ac_no
  FETCH c3 into @cust_ac_no
  END

CLOSE c3
DEALLOCATE c3

1 个答案:

答案 0 :(得分:0)

仅基于提供的代码,(对我而言)它看起来可以用单个光标完成。

假设:

  • 虽然该示例仅显示一个cust_ac_no,但是使用'in()'子句使我认为我们可能需要处理cust_ac_no的列表,因此我将写以支持列表中的多个cust_ac_no
  • 示例代码显示在{strong>相关的cust_ac_no已打印后后打印了notes

一种可能的单光标解决方案:

declare c3 cursor
for
select distinct
       cust_ac_no,
       notes
from   tempdb..M3_SHP_ACCOUNT_NOTES
where  cust_ac_no in ('851243048')  -- could be multiple cust_ac_no's
order by cust_ac_no, inst_seq_no, ord_no, ref_no, acv_no
go

declare @cust_ac_no        varchar(10),
        @cust_ac_no_prev   varchar(10),
        @notes             varchar(4000)

select @cust_ac_no_prev = NULL

open c3

fetch c3 into @cust_ac_no, @notes

while @@sqlstatus = 0
begin
    if @cust_ac_no_prev is NULL
        select @cust_ac_no_prev = @cust_ac_no

    -- print cust_ac_no *after* its associated notes have been printed;
    -- this should be done when we fetch a new cust_ac_no:

    if @cust_ac_no_prev != @cust_ac_no
        print @cust_ac_no_prev

    print @notes

    fetch c3 into @cust_ac_no, @notes
end

-- print the last fetched cust_ac_no:

print @cust_ac_no

close c3
deallocate c3
go