如果您有一个主日期表,您可以简单地查询该表以获取明年的星期一和星期四,并且可以使用 Insert Select ... 语法。
DECLARE @StartDate DateTime
DECLARE @EndDate DateTime
SET @StartDate = '1/1/2013'
SET @EndDate = '12/31/2013'
INSERT INTO DestinationTable(Date,StartTime,EndTime)
SELECT DM.Date,
CASE WHEN DATENAME(dw,DM.Date) = 'Thursday' THEN '1400'
WHEN DATENAME(dw,DM.Date) = 'Monday' THEN '1300'
END AS StartTime,
CASE WHEN DATENAME(dw,DM.Date) = 'Thursday' THEN '1700'
WHEN DATENAME(dw,DM.Date) = 'Monday' THEN '1500'
END AS EndTime
FROM DateMaster DM
WHERE DM.Date Between @StartDate AND @EndDate
AND DATENAME(dw,DM.Date) IN ('Thursday','Monday')
但是,如果您没有主日期表,那么我们可以循环整年并填写表格。
DECLARE @StartDate DateTime
DECLARE @EndDate DateTime
DECLARE @DateVar DateTime
SET @StartDate = '1/1/2013'
SET @EndDate = '12/31/2013'
SET @DateVar = @StartDate
WHILE @DateVar <= @EndDate
BEGIN
INSERT INTO DestinationTable(Date,StartTime,EndTime)
SELECT @DateVar,
CASE WHEN DATENAME(dw,@DateVar) = 'Thursday' THEN '1400'
WHEN DATENAME(dw,@DateVar) = 'Monday' THEN '1300'
END AS StartTime,
CASE WHEN DATENAME(dw,@DateVar) = 'Thursday' THEN '1700'
WHEN DATENAME(dw,@DateVar) = 'Monday' THEN '1500'
END AS EndTime
WHERE DATENAME(dw,@DateVar) IN ('Thursday','Monday')
SET @DateVar = DATEADD(d,1,@DateVar)
END
您可以通过跳其他日子而不是仅仅增加一天来提高效率......
CTE
DECLARE @StartDate DateTime
DECLARE @EndDate DateTime
SET @StartDate = '1/1/2013'
SET @EndDate = '12/31/2013'
;WITH DateMaster(Date)
AS
(
SELECT @StartDate
UNION ALL
SELECT DATEADD(d,1,Date)
FROM DateMaster
WHERE DATEADD(d,1,Date) <= @EndDate
)
INSERT INTO DestinationTable(Date,StartTime,EndTime)
SELECT DM.Date,
CASE WHEN DATENAME(dw,DM.Date) = 'Thursday' THEN '1400'
WHEN DATENAME(dw,DM.Date) = 'Monday' THEN '1300'
END AS StartTime,
CASE WHEN DATENAME(dw,DM.Date) = 'Thursday' THEN '1700'
WHEN DATENAME(dw,DM.Date) = 'Monday' THEN '1500'
END AS EndTime
FROM DateMaster DM
WHERE DM.Date >= @StartDate AND DM.Date <= @EndDate
AND DATENAME(dw,DM.Date) IN ('Thursday','Monday')
OPTION (MAXRECURSION 366)