处理Cursor时出错

时间:2011-07-13 07:07:02

标签: sql sql-server tsql sql-server-2008

代码:

declare C  cursor for SELECT name 
                        FROM [Trial].[dbo].[student]

declare @name varchar(20)
set @name = ''
open C
  fetch from c into @name 
close C
Select @name

任何人都可以帮我解决这个错误:

  

消息207,级别16,状态1,行1无效的列名称“名称”。

1 个答案:

答案 0 :(得分:1)

从您提供的示例中,您的游标用法只是从student表中提取(随机)行。这在功能上等同于以下内容:

declare @name varchar(20)
select @name = select top 1 SName from Trial.dbo.student

如果你正在使用游标,语法应该是这样的:

declare C cursor for select SName from Trial.dbo.student
open C
fetch next from C into @name
while @@fetch_status = 0
    begin
        /* do some work involving @name */
        /* fetch the next row from the cursor */
        fetch next from C into @name
    end
close C
deallocate C

当然,你需要在循环中实际 DO 一些工作,除非你真的试图从学生表中简单地拉出(随机)行。