I’m new to SQL (specifically t-sql and microsoft SQL Server 2008 R2) and had a problem my boss advised me to fix using a cursor. The problem being taking records (equating to shifts entered into a roster) that are over an hour (but divisible by an hour) and effectively splitting them into multiple shift records of an hour each for a report.
Below you can see the section of the query re the cursor logic that I used. My understanding is that cursors are very inefficient and frowned upon – but neither my boss nor myself could identify an alternative solution to this problem.
Can anyone demonstrate a way we could do this without cursors?
Open Curs;
FETCH NEXT FROM Curs INTO @ClientID, @RDNSID, @SvceType, @SDate, @ClientNm, @CHours, @StaffNm, @Package
WHILE (@@Fetch_Status = 0)
BEGIN
SET @Hour = 60
SET @Num = @Chours
IF (@Num % 60 = 0)
BEGIN
WHILE (@Num >= 60)
BEGIN
INSERT INTO #ASRTable VALUES (@ClientID, @RDNSID, @SvceType, @SDate, @ClientNm, @Hour, @StaffNm, @Package)
SET @Num = @Num - 60
SET @SDate = DATEADD(HH, 1, @SDate)
END
END
ELSE
BEGIN
SET @Hour = 'INVALID SHIFT'
INSERT INTO #ASRTable VALUES (@ClientID, @RDNSID, @SvceType, @SDate, @ClientNm, @Hour, @StaffNm, @Package)
END
FETCH NEXT FROM Curs INTO @ClientID, @RDNSID, @SvceType, @SDate, @ClientNm, @CHours, @StaffNm, @Package
END
SELECT * FROM #ASRTable
DROP TABLE #ASRTable
CLOSE Curs
DEALLOCATE Curs