0

我需要使用 T-SQL 2008 R2 复制从 2012 年到 2013 年的所有班次。每天有 3 个班次。开始日期和班次日期始终相同。结束日期(对于班次 c)是第二天。

在此处输入图像描述

如您所见,如果我只使用 dateadd(year, 1, Col),我会得到 2013-02-28 的 2 组记录。第 4、6 和 8 行不应该存在(并且会导致 PK 违规)。第 8 行是错误的,因为 C 班的结束时间应该是前一个日历日。

我总共有 67,000 行要复制

我唯一能想到的就是插入临时表,然后以某种方式识别重复/不正确的记录,删除然后插入回班次表。我相信一定有更好的方法

有人有一个狡猾的计划吗?

我想创建一个通用存储过程,可以将闰年复制到非闰年,反之亦然

问候

标记

4

2 回答 2

0

I figured it out BUT then found some resources were missing shifts for 2012

Ended up creating with tally table and just doing fresh inserts for every shift for the year

SELECT
                    rh.PlanPressID
                    ,DATEADD(hh,(24 / @NoOfShifts) * (t.N - 1),@StartDateTime) AS ShiftStart
                   ,DATEADD(hh,(24 / @NoOfShifts) * (t.N),@StartDateTime) AS ShiftEnd
                   ,CHAR((t.N - 1) % @NoOfShifts + 65) AS ShiftCode
                   ,DATEADD(dd,0,DATEDIFF(dd,0,DATEADD(hh,(24 / @NoOfShifts) * (t.N - 1),@StartDateTime))) AS ShiftDate
                   ,0 AS Personnel
                  FROM
                    dbo.Tally t
                  CROSS JOIN dbo.ResourceHeader AS rh   
于 2012-12-14T23:05:55.830 回答
0

也许尝试一个DISTINCT与 a 结合的列表WHERE End > Start,如这个简化的例子:

CREATE TABLE Shifts(ShiftCode CHAR, ShiftStart DATETIME, ShiftEnd DATETIME);
GO

INSERT Shifts
VALUES('A','2/26/2012 07:00:00','2/26/2012 15:00:00')
, ('B','2/26/2012 15:00:00','2/26/2012 23:00:00')
, ('C','2/26/2012 23:00:00','2/27/2012 07:00:00')
, ('A','2/27/2012 07:00:00','2/27/2012 15:00:00')
, ('B','2/27/2012 15:00:00','2/27/2012 23:00:00')
, ('C','2/27/2012 23:00:00','2/28/2012 07:00:00')
, ('A','2/28/2012 07:00:00','2/28/2012 15:00:00')
, ('B','2/28/2012 15:00:00','2/28/2012 23:00:00')
, ('C','2/28/2012 23:00:00','2/29/2012 07:00:00')
, ('A','2/29/2012 07:00:00','2/29/2012 15:00:00')
, ('B','2/29/2012 15:00:00','2/29/2012 23:00:00')
, ('C','2/29/2012 23:00:00','3/1/2012 07:00:00')
, ('A','3/1/2012 07:00:00','3/1/2012 15:00:00')
, ('B','3/1/2012 15:00:00','3/1/2012 23:00:00')
, ('C','3/1/2012 23:00:00','3/2/2012 07:00:00');
GO

SELECT DISTINCT ShiftCode
, ShiftStart = DATEADD(YYYY,1,ShiftStart)
, ShiftEnd = DATEADD(YYYY,1,ShiftEnd)
FROM Shifts
WHERE DATEADD(YYYY,1,ShiftEnd) > DATEADD(YYYY,1,ShiftStart)
ORDER BY DATEADD(YYYY,1,ShiftStart), ShiftCode
GO

结果:

A         2013-02-26 07:00:00.000 2013-02-26 15:00:00.000
B         2013-02-26 15:00:00.000 2013-02-26 23:00:00.000
C         2013-02-26 23:00:00.000 2013-02-27 07:00:00.000
A         2013-02-27 07:00:00.000 2013-02-27 15:00:00.000
B         2013-02-27 15:00:00.000 2013-02-27 23:00:00.000
C         2013-02-27 23:00:00.000 2013-02-28 07:00:00.000
A         2013-02-28 07:00:00.000 2013-02-28 15:00:00.000
B         2013-02-28 15:00:00.000 2013-02-28 23:00:00.000
C         2013-02-28 23:00:00.000 2013-03-01 07:00:00.000
A         2013-03-01 07:00:00.000 2013-03-01 15:00:00.000
B         2013-03-01 15:00:00.000 2013-03-01 23:00:00.000
C         2013-03-01 23:00:00.000 2013-03-02 07:00:00.000
于 2012-12-14T19:13:30.483 回答