I am trying to avoid cursor to get the following desired output from current format. Currently I have to use a cursor and since the dataset is very huge it takes me around 2 hours to run it. Is there a way to avoid cursor
Declare @CustomerId CHAR(8)
Declare @StartDate DateTime
Declare @PlStartDate DateTime
Declare @ProviderNo CHAR(8)
Declare @Code CHAR(3)
Declare @PreviousCustomerId CHAR(8)
Declare @PreviousStartDate DateTime
Declare @PreviousRealStartDate DateTime
Declare @PreviousProviderNo CHAR(8)
Declare @PreviousCode CHAR(3)
Declare @RowNumber smallint
Declare @providers CURSOR
SET @providers = CURSOR FAST_FORWARD FOR
Select CustomerId, StartDate, PlStartDate, ProviderNo, Code, ProviderSSN, RowNumber
From dbo.[provider] ORDER by CustomerId, StartDate
OPEN @providers
FETCH NEXT From @providers INTO @CustomerId, @StartDate, @PlStartDate,@ProviderNo, @Code, @ProviderSSN, @RowNumber
WHILE @@FETCH_STATUS = 0
BEGIN
If @RowNumber <>1 AND @CustomerId = @PreviousCustomerId AND @Code = @PreviousCode AND (@ProviderNo = @PreviousProviderNo)
BEGIN
Update dbo.provider
SET StartDate = @PreviousRealStartDate
Where CustomerId = @CustomerId AND StartDate = @StartDate;
END
ELSE
BEGIN
Set @StartDate = @StartDate;
Update dbo.provider
Set StartDate = @StartDate
Where CustomerId = @CustomerId AND StartDate = @StartDate
END
Set @PreviousCustomerId = @CustomerId
Set @PreviousCode = @Code
Set @PreviousProviderNo = @ProviderNo
if @StartDate IS NOT NULL
Set @PreviousRealStartDate = @StartDate
Set @PreviousStartDate = @StartDate
FETCH NEXT From @providers INTO @CustomerId, @StartDate, @PlStartDate,@ProviderNo, @Code, @RowNumber
END
CLOSE @providers
DEALLOCATE @providers
Current Format
Cust ID Start Date End Date Code Provider 7063903 2/11/2009 2/17/2009 DEF 485960 7063903 2/17/2009 2/24/2009 DEF 485960 7063903 2/24/2009 4/6/2009 LHF 479407 7063903 4/6/2009 9/11/2009 DEF 487398 7063903 8/31/2010 9/1/2010 DEF 487398 7063903 8/28/2011 11/25/2011 ABC 531428 7063903 3/1/2012 6/25/2012 DEF 487398 7063903 6/25/2012 3/22/2013 DEF 487398 7063903 3/22/2013 4/23/2014 DEF 487398 7063903 4/23/2014 5/1/2014 DEF 487398 7063903 5/1/2014 7/1/2015 DEF 487398 7063903 7/1/2015 8/28/2015 DEF 531428 7063903 8/28/2015 11/25/2015 ABC 531428 7063903 11/25/2015 9/21/2016 ABC 531428 Desired Output CustID Start Date End Date Code Provider 7063903 2/11/2009 2/24/2009 DEF 485960 7063903 2/24/2009 4/6/2009 LHF 479407 7063903 4/6/2009 9/1/2010 DEF 487398 7063903 8/28/2011 11/25/2011 ABC 531428 7063903 4/6/2009 7/1/2015 DEF 487398 7063903 7/1/2015 8/28/2015 DEF 531428 7063903 8/28/2015 9/21/2016 ABC 531428

