What is a cursor?
For the table structure in this instance, see the document "Create a table, insert an id column, and automatically generate an id ".
Use yuyongTest;
Declare @ tot int;
Set @ tot = 0;
Declare @ name nvarchar (50 );
Set @ name = '';
-- Select a column to define the cursor. The cursor serves to traverse the table.
Declare stuName cursor
For
Select Name from student;
-- Open the cursor
Open stuName;
-- Move the cursor down (the first row of data is migrated at the beginning) and assign the current value of the cursor to the variable.
Fetch nextfrom stuName Into @ name;
-- @ Fetch_Status indicates the execution status of the fetch statement.
-- 0 indicates that the FETCH statement is successful.
---1 indicates that the FETCH statement fails or this row is not in the result set.
---2 indicates that the extracted row does not exist.
While (@ Fetch_Status = 0) begin
If (@ name = 'qw ')
Set @ tot = @ tot + 1;
Fetch Next From stuNameInto @ name;
End
-- Close the cursor
Close stuName;
-- Release cursor
Deallocate stuName;
Select @ tot;
Select COUNT (*) fromstudent where name = 'qw'
Execution result: