What is cursor?
A
cursor can be viewed as a pointer to one row in a set of rows. The
cursor can only reference one row at a time, but can move to other rows
of the result set as needed.
To use cursors in SQL procedures, you need to do the following:
- Declare a cursor that defines a result set.
- Open the cursor to establish the result set.
- Fetch the data into local variables as needed from the cursor, one row at a time.
- Close the cursor when done
To work with cursors you must use the following SQL statements:
- DECLARE CURSOR
- OPEN CURSOR
- FETCH ROW By ROW
- CLOSE CURSOR
Example
Create the table of Employee
CREATE TABLE Employee
(
EID INT PRIMARY KEY IDENTITY,ENAME VARCHAR(50),SALARY DECIMAL(10,2),DEPT VARCHAR(50)
)
INSERT INTO Employee(ENAME,SALARY,DEPT)VALUES('ABC',2000.00,'HR')
INSERT INTO Employee(ENAME,SALARY,DEPT)VALUES('XYZ',4000.00,'SUPPORT')
INSERT INTO Employee(ENAME,SALARY,DEPT)VALUES('DEF',6000.00,'SUPPORT')
INSERT INTO Employee(ENAME,SALARY,DEPT)VALUES('PQR',1000.00,'HR')
INSERT INTO Employee(ENAME,SALARY,DEPT)VALUES('MNL',7000.00,'MARKETING')
INSERT INTO Employee(ENAME,SALARY,DEPT)VALUES('OPQ',6000.00,'HR')
INSERT INTO Employee(ENAME,SALARY,DEPT)VALUES('RST',9000.00,'ACCOUNT')
SELECT * FROM Employee
Now we are updating salary 20% row by row
DECLARE @EID VARCHAR(50)
DECLARE db_cursor CURSOR FOR
SELECT EID FROM Employee
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @EIDWHILE @@FETCH_STATUS = 0BEGINUPDATE Employee SET SALARY=SALARY+(SALARY*0.20)WHERE EID=@EIDFETCH NEXT FROM db_cursor INTO @EIDEND
CLOSE db_cursor
DEALLOCATE db_cursor
Result
No comments:
Post a Comment