Cursor in Sql Server
In this article i will discuss how to use Cursor in Sql. A cursor is used to processed result set sequentially. In SQL procedures, a cursor makes it possible to define a set of data rows and perform complex logic on a row by row basis.
Syntaxes of cursor
In this example printing First Name & Last Name using Cursor.
Syntaxes of cursor
- SET \ SELECT Statement - It initialize the variables.
- DECLARE Statement-It Declare variables .
- DECLARE CURSOR Statement - Declaring a cursor in scope.
- OPEN statement - Open the cursor to begin data row processing.
- FETCH NEXT Statement- Fetch next row from result set.
- WHILE Statement -Loops until rows remains for processing.
- BEGIN...END Statement - Start and end of the code block
- CLOSE statement - Releases the current data and associated locks, but permits the cursor to be re-opened.
- DEALLOCATE Statement - It Destroys the cursor
DECLARE @FirstName varchar(50), @LastName varchar(50) DECLARE cursorName CURSOR -- Declare cursor LOCAL SCROLL STATIC FOR Select firstName, lastName FROM myTable OPEN cursorName -- open the cursor FETCH NEXT FROM cursorName INTO @fName, @LastName PRINT @FirstName + ' ' + @LastName -- print the name WHILE @@FETCH_STATUS = 0 BEGIN FETCH NEXT FROM cursorName INTO @fName, @LastName PRINT @FirstName + ' ' + @LastName -- print the name END CLOSE cursorName -- close the cursor DEALLOCATE cursorName -- Deallocate the cursor
In this example printing First Name & Last Name using Cursor.
0 comments :
Post a Comment