Know SQL CURSOR


It’s a database object used by applications to control data in a set of row by row basis. The difference in general SQL COMMANDS and CURSOR is SQL commands perform action in one time while cursor executes records in row by row basis.
You first need to declare the CURSOR before using it. Once CURSOR has been declared, you can open the CURSOR and fetch it. You can fetch the record on row by row basis and make operation on current active row. After completion of fetching the record from CURSOR you need to close it and deallocate it to release SQL server resources.
Here is the example, try it
DECLARE  @iRowId  int,

         @Name varchar(55),

         @Age int   

-- declare Curosr

DECLARE cusrorName CURSOR FOR

SELECT    testId, cName, Age FROM TestTable

--open Curosr
OPEN cusrorName

FETCH cusrorName INTO @iRowId, @Name, @Age

--start the loop

WHILE @@Fetch_Status = 0

   BEGIN

-- here you are fetching records on basis of row by row i.e by passing @iRowId = 1
-- will fetch all records which is having test Id 1 from TestTable
  
   IF (@iRowId = 1)
  
      BEGIN
            PRINT @Name
      END

  FETCH cusrorName INTO @iRowId, @Name,@Age          

   END

CLOSE cusrorName

DEALLOCATE cusrorName

Comments