About Me

My photo
a Dynamic and Energetic guy.....

Sunday, March 8, 2009

How to write a Stored Procedure with a Cursor

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: chanaka
-- Create date: 04/03/2009
-- Description:
-- =============================================
CREATE PROCEDURE dbo.SearchRegionWise
-- Add the parameters for the stored procedure here
@firstPara nvarchar(25),
@secondPara nvarchar(25)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

-- Insert statements for procedure here
DROP TABLE TemporySearchData
CREATE TABLE TemporySearchData(OfferID nvarchar(50), UserID nvarchar(50), StartLocation nvarchar(100), Destination nvarchar(100))
DECLARE @firstName nvarchar(25)
DECLARE @nextName nvarchar(25)
DECLARE @addString nvarchar(25)
DECLARE @UserID nvarchar(50)
DECLARE @StartLocation nvarchar(50)
DECLARE @Destination nvarchar(50)

DECLARE firstCursor CURSOR FOR (SELECT LocationName FROM dbo.tblLocation WHERE (RegionId =
(SELECT RegionId FROM dbo.tblLocation AS tblLocation_1 WHERE (LocationName = @firstPara))))
OPEN firstCursor
FETCH NEXT FROM firstCursor INTO @firstName
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @firstName

DECLARE loopCursor CURSOR READ_ONLY FOR (SELECT LocationName FROM dbo.tblLocation WHERE (RegionId =
(SELECT RegionId FROM dbo.tblLocation AS tblLocation_1 WHERE (LocationName = @secondPara))))
OPEN loopCursor
FETCH NEXT FROM loopCursor INTO @nextName
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @nextName

DECLARE loopInfo CURSOR READ_ONLY FOR (SELECT DISTINCT dbo.tblTravelOffer.tblTravelId, dbo.tblTravelOffer.UserId, dbo.tblTravelOffer.StartLocation, dbo.tblTravelOffer.Destination FROM dbo.tblTravelOffer WHERE dbo.tblTravelOffer.StartLocation = @firstName AND dbo.tblTravelOffer.Destination = @nextName)
OPEN loopInfo
FETCH NEXT FROM loopInfo INTO @addString, @UserID, @StartLocation, @Destination
WHILE @@FETCH_STATUS = 0
BEGIN
INSERT INTO TemporySearchData (OfferID, UserID, StartLocation, Destination)
VALUES (@addString, @UserID, @StartLocation, @Destination)
FETCH NEXT FROM loopInfo INTO @addString, @UserID, @StartLocation, @Destination
END
CLOSE loopInfo
DEALLOCATE loopInfo
FETCH NEXT FROM loopCursor INTO @nextName
END
CLOSE loopCursor
DEALLOCATE loopCursor
FETCH NEXT FROM firstCursor INTO @firstName
END
CLOSE firstCursor
DEALLOCATE firstCursor
select * from dbo.TemporySearchData
END
GO

No comments:

My Masters