-1

我目前在 SQL Server 中有这个表:

PL_ID User_ID Log_Date Out_Time In_Time 原因详情

PL 代表人员记录器...然后您有用户 ID、日志日期(休息日)、外出时间、及时、原因和详细信息...有一个 ASP 前端允许用户添加他们的日期进入由其他人编写的表格...目前用户能够自己执行此操作不是问题但是,我被赋予了为下一年增加员工休假日的任务...他们正在重复休息日(每周一下午 1 点至下午 3 点)或(每周四 2 点至 5 点)......必须有一种更简单的方法来做到这一点,而不是一次只增加一天的休息时间。我已经尝试过使用 dateadd 进行试验,但我无法弄清楚将其包含在插入中的语法......有一天我计划将其添加到用户页面,但现在我只需要让他们的休息日进入表格!

提前谢谢你们,

汤姆。

4

1 回答 1

0

如果您有一个主日期表,您可以简单地查询该表以获取明年的星期一和星期四,并且可以使用 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) 
于 2012-09-21T15:11:16.767 回答