Sybase ASE:如何使用游标打印所有表行?



下面的代码应该打印临时表#table_A中包含的所有行:

create table #table_A
(
ID                  int          NULL ,
foo                 int          NULL 
)
go
insert into #table_A values (1, 2)
insert into #table_A values (2, 3)
go
declare c_table_A cursor                     
for select *                                    
from #table_A                      
order                                      
by 1                                                                      
open c_table_A                               
fetch c_table_A                            
while @@sqlstatus = 0                             
begin                                           
print '%1!', c_table_A                 
fetch c_table_A                        
end                                             
close c_table_A   

go  

但是,它会导致以下错误消息:

DECLARE CURSOR must be the only statement in a query batch.  

如何打印(临时(表中包含的所有行?


这是提出我的问题的另一种方式:

我正在尝试做这样的事情:

open c_table_A                               
fetch c_table_A into @record_variable                           
while @@sqlstatus = 0                             
begin                                           
print '%1!', @record_variable
fetch c_table_A into @record_variable                       
end                                             
close c_table_A   

有没有办法在 sybase 中声明一个包含一整行表的变量?


附言:只需使用"从...中选择*..."对我不起作用。在打印行之前,我需要对每一行做一些事情。(我的问题应该集中在基本部分,这就是为什么我没有进一步详细介绍我需要对每一行做的其他事情(

感谢您的澄清。

在 SQL 批处理中,游标声明必须与使用它的批处理分开,而不是存储过程,因此declare cursor和后续批处理之间需要有一个go

抱歉,无法在 Sybase ASE 中定义"行变量"。返回到变量的每一列都必须为其声明一个变量。在下面的示例中,@id 和 @foo 声明为与表中的列 id 和 foo 相同的类型。其他RDBMS确实有"记录数据类型",但不幸的是没有Sybase ASE。

在承诺使用游标(在大型表上游标相对较慢(之前,您可以在 select 语句中执行其他处理。如果存在条件逻辑case ... when ... then ... else ... end可能会证明很有用,尽管无法直接从 select 语句中调用存储过程,但可以调用 SQL 用户定义的函数。如果您需要帮助,这可能是一个单独的问题。

我还添加了一个deallocate cursor语句,它是语法的一部分,可释放与您的连接关联的内部工作区。

您可能希望在运行批处理之前执行set nocount on,它会删除有时烦人的(1 row affected)消息。


set nocount on
go
create table #table_A
(
ID                  int          NULL ,
foo                 int          NULL 
)
go
insert into #table_A values (1, 2)
insert into #table_A values (2, 3)
go
declare c_table_A cursor                     
for select *                                    
from #table_A                      
order                                      
by 1                                                                      
go
declare
@id     int,
@foo    int
open c_table_A                               
fetch c_table_A into @id, @foo
while @@sqlstatus = 0                             
begin                                           
print 'id: %1! foo: %2!', @id, @foo
fetch c_table_A into @id, @foo
end                                             
close c_table_A   
go 
deallocate cursor c_table_A
go

最新更新