为什么我的光标工作然后在 SQL 中中断



这是我的代码。它穿过一个表格,该表格包含公司成立的年份,并且应该每年从行中逐个提取并打印出来。

  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,级别 16,状态 1,第 10 行 具有名称的游标 "年游标"不存在。Msg 16916,级别 16,状态 1,第 14 行 A 名称为"YearsCursor"的游标不存在。消息 16916,级别 16,状态 1,第 26 行 名称为"YearsCursor"的游标不 存在。Msg 16916,级别 16,状态 1,第 27 行 具有名称的游标 "年游标"不存在。

如果使用游标变量名:

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

或检查语法光标https://learn.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

这样定义光标

声明年份光标 CURSOR 为

 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 

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

相关内容

最新更新