最近做一个项目,数据库是sybase11.5版的,此文是开发过程中问题的解决方法。
不常用Sybase数据库,首先说明需求,因为需要提取一些历史数据插入到另外的一张表里,自己就写了一段sql代码,大致如下:
declare @aa varchar(10)
declare cur_Test CURSOR for select BH,MC from tab1 where TM between time1 and time2
begin
open cur_Test
fetch cur_Test into @aa
while @@sqlstatus = 0
begin
insert into tb1(DJ) values(@aa)
fetch cur_Test into @aa
end
close cur_Test
deallocate cursor cur_Test
end
在执行的时候,总是在定义游标的行提示DECLARE CURSOR must be the only statement in a query batch.相当的郁闷,这如果是在mssql里肯定是可以的。还有一点就是如果把这段代码放到一个触发器里执行的话,也是完全没有问题的。
多方求教,最后一个朋友告诉我说,在写成这样的代码的时候,代码需要调整一下,如下:
declare cur_Test CURSOR for select BH,MC from tab1 where TM between time1 and time2
begin
declare @aa varchar(10)
open cur_Test
fetch cur_Test into @aa
while @@sqlstatus = 0
begin
insert into tb1(DJ) values(@aa)
fetch cur_Test into @aa
end
close cur_Test
deallocate cursor cur_Test
end
调整之后呢,还有最重要的一点就是要先单独执行一下,declare cur_Test……这句代码,然后再选中剩下的全部代码执行,成功提取。