光标未打开

时间:2012-08-14 18:13:25

标签: sql sybase-iq

我正在尝试使用存储在表中的语句来创建表。我正在使用带有execute(sql)的游标,如下所示:

create table tab
(
  CreateSql varchar(250)
)

insert into tab values ('create table tab1 (id int )')
insert into tab values ('create table tab2 (id int )')
insert into tab values ('create table tab3 (id int )')

  declare cur cursor for
    select createsql
      from tab  

  declare @sql varchar(255)

  open cur
  fetch cur into @sql

  while @@SqlStatus = 0
    begin           
      execute(@Sql)               
      fetch cur into @sql
    end

  close cur
  deallocate cursor cur

如果我运行它,则会出现错误:

  

无法执行语句。光标未打开SQLCODE = -180,ODBC 3   状态= “34000”

第一个表(tab1)将创建,但其他(tab2,tab3)表不会。

如果我用select sql替换语句execute(sql),脚本将正常工作。

提前感谢您的回答。

PX

3 个答案:

答案 0 :(得分:1)

为什么不使用while循环。在这些场景中使用Cursor是过度的。 我不熟悉sybase语法,但在SQL Server 2008中你可以这样做

create table tab
(
  CreateSql varchar(250)
  ,ID int IDENTITY(1,1) 
)

insert into tab values ('create table tab1 (id int )')
insert into tab values ('create table tab2 (id int )')
insert into tab values ('create table tab3 (id int )')

DECLARE @max INT = (SELECT MAX(ID) FROM tab) 
    ,@index int =1
    ,@sql varchar(255)


  while (@index<= @max  )
    begin           

      select @sql= createsql   from tab WHERE ID=@index

      execute(@Sql)  

      SET @index = @index+1
    end

答案 1 :(得分:1)

IQ喜欢在第一次提交后关闭光标。

您需要使用WITH HOLD子句(或沿着这些行的某些东西)来保持光标打开。

答案 2 :(得分:0)

我不是sybase专家,但看起来你在fetch语句中缺少了。

    fetch next cur into @sql
相关问题