Thursday, 22 June 2017

Looping With Cursor SQL Server

Cursor is an database object which is use when there is a need to process table record row by row . you can access each field of your table at record by record.In relational databases, operations are made on a set of rows. For example, a SELECT statement returns a set of rows which is called a result set. Sometimes the application logic needs to work with a row at a time rather than the entire result set at once. In T-SQL, one way of doing this is using a CURSOR. For example when we want to get record from one table and need to insert into another with performing some logic or some conditions .For example if we want to get value from one table row by row  and need to perform some logic over that and update /insert into another table then we can use cursors. Cursor basically works as for/While loop.

USE [Girfa_tportal]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
alter procedure [dbo].[GetStudentContact]
as
begin
Declare @phone as varchar(15)
Declare @email as varchar(50)


Declare MY_data CURSOR FOR
select Phone,email from [dbo].[StudentMaster]
open MY_data
FETCH NEXT FROM MY_data INTO @phone ,@email
        WHILE @@FETCH_STATUS = 0
        BEGIN

           select @phone as contact,@email as Email

        FETCH NEXT FROM MY_data INTO @phone ,@email
        END
    CLOSE MY_data
DEALLOCATE MY_data

end


No comments:

Post a Comment