Search This Blog

Thursday, July 25, 2019

Cursors in SQL

A cursor is a temporary work area created in system memory when a SQL statement is executed
a cursor can hold more than one row, but can process only one row at a time



Types of Cursors

There are the following two types of Cursors:
  1. Implicit Cursor
  2. Explicit Cursor
Implicit Cursor
These types of cursors are generated and used by the system during the manipulation of a DML query (INSERT, UPDATE and DELETE). An implicit cursor is also generated by the system when a single row is selected by a SELECT command.

Explicit Cursor
This type of cursor is generated by the user using a SELECT command. An explicit cursor contains more than one row, but only one row can be processed at a time. An explicit cursor moves one by one over the records. An explicit cursor uses a pointer that holds the record of a row. After fetching a row, the cursor pointer moves to the next row.


DECLARE  @b INT =0;

DECLARE @MemberId INT   
    DECLARE db_Lotterycursor CURSOR  FOR
SELECT userid   FROM tblUserInfo ORDER BY userid
     OPEN db_Lotterycursor
  FETCH NEXT FROM db_Lotterycursor INTO @MemberId
       WHILE @@FETCH_STATUS = 0
   BEGIN 
    DECLARE @nam NVARCHAR(50)
         SET  @b=@MemberId;
         SET @nam = (SELECT tblUserInfo.AccountNo  FROM  tblUserInfo  WHERE UserID =@b)
         UPDATE Members SET Members.Email  =@nam  WHERE MemberId =@b
      

  FETCH NEXT FROM db_Lotterycursor INTO  @MemberId
  END
 
    CLOSE db_Lotterycursor
        DEALLOCATE db_Lotterycursor

No comments :