To know how to create basic cursor, and what is cursor, types, scope etc. please read this post. To know how to create scroll cursor, read this post.
In this post, we shall understand how to create a cursor in SQL Server and store it's data into a temporary table variable and then take output from it.
Let's see this with example.
-- Declare variables to hold cursor data for each record
DECLARE @AutoIdC int
DECLARE @FirstNameC varchar(50)
DECLARE @LastNameC varchar(50)
-- declare table to hold temporary data
DECLARE @myTable as TABLE
(
PersonId int,
FullName varchar(100)
)
-- declare cursor
DECLARE myCursor CURSOR FOR
SELECT AutoId, FirstName, LastName FROM PersonalDetails
WHERE AutoId > 1100 -- put more where clause if any
-- open
OPEN myCursor
-- fetch records from the cursor
FETCH NEXT FROM myCursor INTO @AutoIdC, @FirstNameC, @LastNameC
WHILE @@FETCH_STATUS = 0
BEGIN
INSERT INTO @myTable(PersonId, FullName) VALUES
(@AutoIdC, @FirstNameC + ' ' + @LastNameC)
FETCH NEXT FROM myCursor INTO @AutoIdC, @FirstNameC, @LastNameC
END
CLOSE myCursor -- must to close
DEALLOCATE myCursor -- must to deallocate
-- Filter the output from the temp table if needed or just get all
SELECT * FROM @myTable WHERE FullName LIKE 'S%'
In above code snippet, we have done following
Output
Views: 16608 | Post Order: 118