Hi,
I've written a cursor to update a data set using a cursor. The problem is that it takes a long time to run and it needs to be done regularly. There must be a better way to do it, but I've taught myself and can't identify another way.
I have 2 tables:
- Master Table - Approx 160,000 rows with a yardage start and end point. Each row is no more than 220 yards
- Plan table - approx 80,000 rows with a yardage start and end point. each row could be any number of yards (usually upwards of 10,000 yards)
I'm basically trying to return the next date each 220 yard section will be checked.
[[DECLARE @strRowsAffected NVARCHAR(400), @TRKELR NVARCHAR(20), @TRKTrackID INT, @TRVVehicle Nvarchar(50), @ShiftCode nvarchar(50)
DECLARE @TRVTotalENDYards BIGINT, @TRVTotalSTARTYards BIGINT, @ShiftDate DATE, @UXSwap BIGINT
DECLARE TRKCURSOR CURSOR
FOR SELECT DISTINCT ELR, TrackID FROM tbl_TRVTrainPlanData
WHERE ELR IS NOT NULL
ORDER BY ELR, TrackID
OPEN TRKCURSOR
FETCH NEXT FROM TRKCURSOR
INTO @TRKELR, @TRKTrackID
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE TRVCURSOR CURSOR
FOR SELECT ShiftDate, TotalStartYards, TotalFinishYards, Vehicle, ShiftCode FROM tbl_TRVTrainPlanData
WHERE ELR = @TRKELR AND TrackID = @TRKTrackID
ORDER BY ShiftDate ASC
OPEN TRVCURSOR
-- FETCH THE FIRST DATA ROW FOR LOADED ELR AND TRACK ID
FETCH NEXT FROM TRVCURSOR
INTO @ShiftDate, @TRVTotalStartYards, @TRVTotalENDYards, @TRVVehicle, @ShiftCode
WHILE @@FETCH_STATUS = 0
BEGIN
IF (@TRVTotalEndYards < @TRVTotalSTARTYards)
BEGIN
set @UXSwap = @TRVTotalEndYards
set @TRVTotalEndYards = @TRVTotalSTARTYards
set @TRVTotalSTARTYards = @UXSwap
END
UPDATE tbl_MasterTrackInfo_TrackGeo SET NextRecordingDate = @ShiftDate, NextDateVehicle = @TRVVehicle
WHERE ELR = @TRKELR
AND TrackID = @TRKTrackID
AND ((TotalStartyards >= @TRVTotalStartYards AND TotalStartYards < @TRVTotalEndYards)
OR (TotalFinishYards > @TRVTotalStartYards AND TotalFinishYards <= @TRVTotalEndYards)
OR ((@TRVTotalStartYards >= TotalStartyards AND @TRVTotalSTARTYards < TotalFinishYards)
AND (@TRVTotalEndYards > TotalStartyards AND @TRVTotalENDYards <= TotalFinishYards)))
AND (NextRecordingDate IS NULL OR NextRecordingDate > @ShiftDate)
and (@ShiftDate >= GETDATE())
FETCH NEXT FROM TRVCURSOR
INTO @ShiftDate, @TRVTotalStartYards, @TRVTotalENDYards, @TRVVehicle, @ShiftCode
END
CLOSE TRVCURSOR
DEALLOCATE TRVCURSOR
FETCH NEXT FROM TRKCURSOR
INTO @TRKELR, @TRKTrackID
END
CLOSE TRKCURSOR
DEALLOCATE TRKCURSOR]](http://txt)