- The Cursors are used to loop through the Result of SQL Statement.
- This Bellow example shows how to create and loop through the Resulted temp table.
CREATE TABLE #temp
(
name VARCHAR(20),
Salary MONEY
)
INSERT
INTO #temp VALUES
(
'Siva',
20000
)
INSERT
INTO #temp VALUES
(
'Babu',
25000
)
INSERT
INTO #temp VALUES
(
'Raghu',
15000
)
SELECT *
FROM #temp
GO
-- Declaring the Variables to hold the Values
DECLARE @EMPNAME VARCHAR(20) ;
DECLARE @Salary MONEY;
-- Declaring the cursor for accessing the Resulted Records.
DECLARE @NameCursor
CURSOR
-- To refering the Selected values for the cursour
SET @NameCursor=
CURSOR FOR
SELECT NAME,
SALARY
FROM #temp
-- To Open the Cursor and Fetch the Record and Assign to variables
OPEN @NameCursor
FETCH NEXT
FROM @NameCursor
INTO @EMPNAME,
@Salary
-- Loop through the entire Result based on the Resultset
WHILE @@FETCH_STATUS=0
BEGIN
-- Print the Result as you like
PRINT @EMPNAME +'''s Salary:' + CAST(@Salary AS VARCHAR(10))
FETCH NEXT
FROM @NameCursor
INTO @EMPNAME,
@Salary
END
-- Close the cursor
CLOSE @NameCursor
-- Deallocate cursor
DEALLOCATE @NameCursor
--Result
--------
Siva's Salary:20000.00
Babu's Salary:25000.00
Raghu's Salary:15000.00



Read User's Comments