为什么我的光标会在SQL

时间:2017-11-07 10:02:48

标签: sql-server

这是我的代码。它贯穿一个公司成立多年的桌子,它应该每年从一行中拉出并打印出来。

  DECLARE @Yearfounded int
--Now I am going to start work on the cursor

DECLARE @YearsCursor CURSOR 
Select [YEar] From dbo.YearsRunning

OPEN YearsCursor

FETCH NEXT FROM YearsCursor into @Yearfounded

WHILE @@FETCH_STATUS = 0

Begin

Print @Yearfounded

Fetch Next From YearsCursor into @Yearfounded

End

Close YearsCursor
Deallocate YearsCursor

这是我得到的错误

  

Msg 16916,Level 16,State 1,Line 10带有名称的光标   ' YearsCursor'不存在。 Msg 16916,Level 16,State 1,Line 14 A.   光标名称为' YearsCursor'不存在。 Msg 16916,等级   16,状态1,第26行一个名为' YearsCursor'的光标。才不是   存在。消息16916,级别16,状态1,行27具有名称的游标   ' YearsCursor'不存在。

3 个答案:

答案 0 :(得分:1)

如果使用游标变量名:

DECLARE @YearsCursor CURSOR  
SET @YearsCursor  =CURSOR FOR  Select  Select [YEar] From dbo.YearsRunning

或检查语法光标 https://docs.microsoft.com/en-us/sql/t-sql/language-elements/declare-cursor-transact-sql

  DECLARE @Yearfounded int
--Now I am going to start work on the cursor

DECLARE YearsCursor CURSOR FOR Select [YEar] From dbo.YearsRunning

OPEN YearsCursor

FETCH NEXT FROM YearsCursor into @Yearfounded

WHILE @@FETCH_STATUS = 0

Begin

Print @Yearfounded

Fetch Next From YearsCursor into @Yearfounded

End

Close YearsCursor
Deallocate YearsCursor

答案 1 :(得分:0)

像这样定义光标

DECLARE YearsCursor CURSOR

答案 2 :(得分:-1)

 DECLARE @Yearfounded int
--Now I am going to start work on the cursor

DECLARE @YearsCursor CURSOR 
Select [YEar] From dbo.YearsRunning

    OPEN @YearsCursor

FETCH NEXT FROM YearsCursor into @Yearfounded

WHILE @@FETCH_STATUS = 0

Begin

Print @Yearfounded

Fetch Next From YearsCursor into @Yearfounded

End

Close @YearsCursor
Deallocate @YearsCursor 

您在打开关闭和取消分配光标时忘记添加@