2

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
4

1 回答 1

1

好吧,您没有给我们样本数据或预期结果,但我认为这遵循相同的逻辑:

declare @t table (
    SDate datetime not null,
    Chours int not null --Curiously, will store a number of minutes?
)

insert into @t (SDate,Chours) values ('2012-12-19T10:30:00',120),('2012-12-18T09:00:00',60),('2012-12-17T08:00:00',90)

;with shifts as (
    select SDate,Chours,'60' as Hour from @t where Chours % 60 = 0
    union all
    select DATEADD(hour,1,SDate),CHours - 60,'60' from shifts where Chours > 0
)
select SDate,Hour from shifts
union all
select SDate,'Invalid Shift' from @t where CHours % 60 <> 0

结果:

SDate                   Hour
----------------------- -------------
2012-12-19 10:30:00.000 60
2012-12-18 09:00:00.000 60
2012-12-18 10:00:00.000 60
2012-12-19 11:30:00.000 60
2012-12-19 12:30:00.000 60
2012-12-17 08:00:00.000 Invalid Shift

当然,我没有你所有的其他专栏,因为我不知道它们是什么意思。

于 2012-12-19T07:25:54.493 回答