我浏览了论坛,找不到完全符合我的问题的任何内容。此查询应该为员工添加定期假期。如果我排除 PL_ID 变量并且只有一个没有主键的表,则代码会添加在 case 语句中定义的正确日期假期,这是在测试表上,但需要添加到具有超过 25,000 个条目的表中。
该表包括 PL_ID、Log_Date、Out_Time、In_Time
我目前有这个代码:
DECLARE @StartDate DateTime
DECLARE @EndDate DateTime
DECLARE @DateVar DateTime
DECLARE @PL_ID int
SET @StartDate = '1/10/2012'
SET @EndDate = '1/11/2012'
SET @DateVar = @StartDate
SET @PL_ID = 0
WHILE @DateVar <= @EndDate
BEGIN
INSERT INTO Logger_test2(PL_ID,Log_Date,In_Time,Out_Time)
SELECT @PL_ID,@DateVar,
CASE WHEN DATENAME(dw,@DateVar) = 'Thursday' THEN '9'
WHEN DATENAME(dw,@DateVar) = 'Monday' THEN '12'
END AS In_Time,
CASE WHEN DATENAME(dw,@DateVar) = 'Thursday' THEN 'After 5'
WHEN DATENAME(dw,@DateVar) = 'Monday' THEN 'After 5'
END AS Out_Time
WHERE DATENAME(dw,@DateVar) IN ('Thursday','Monday')
SET @DateVar = DATEADD(d,1,@DateVar)
UPDATE Logger_test2 set @PL_ID = PL_ID = @PL_ID +1
END
使用此代码,它只会在具有最大 PL_ID 的表中添加一行,但我需要它为每个条目创建一个新 ID,抱歉,它有点模糊。真的很感谢你的帮助!
现在离得到它更近了!但是,如果我将日期更改为下个月,则会出现重复的键错误:消息 2627,级别 14,状态 1,第 15 行违反主键约束“PK_Logger_test2”。无法在对象“dbo.Logger_test2”中插入重复键。重复键值为 (4) - 是否有另一种方法可以避免插入重复键?
已解决:这是完整的代码:),很有魅力,让我的生活更轻松!只需更改用户ID,即可输入每个人预定的明年假期:
DECLARE @StartDate DateTime
DECLARE @EndDate DateTime
DECLARE @DateVar DateTime
DECLARE @PL_ID int
DECLARE @User_ID int
DECLARE @Reason nvarchar(50)
DECLARE @Details nvarchar (500)
SET @StartDate = '30/09/2012'
SET @EndDate = '24/12/2012'
SET @DateVar = @StartDate
SET @User_ID = 55
SET @Reason = 'Day off'
SET @Details = 'Day off'
--SET @PL_ID = 0
SELECT @PL_ID = max(PL_ID) from People_Logger
WHILE @DateVar <= @EndDate
BEGIN
select @PL_ID = @PL_ID +1
SET IDENTITY_INSERT dbo.People_logger ON;
INSERT INTO People_Logger(PL_ID,LOG_Date,User_ID,Reason,Details,In_Time,Out_Time)
SELECT @PL_ID,@DateVar,@User_ID,@Reason,@Details,
CASE WHEN DATENAME(dw,@DateVar) = 'Thursday' THEN 'After 5'
WHEN DATENAME(dw,@DateVar) = 'Friday' THEN 'After 5'
END AS In_Time,
CASE WHEN DATENAME(dw,@DateVar) = 'Thursday' THEN '9'
WHEN DATENAME(dw,@DateVar) = 'Friday' THEN '9'
END AS Out_Time
WHERE DATENAME(dw,@DateVar) IN ('Thursday','Friday')
SET IDENTITY_INSERT dbo.People_Logger OFF;
SET @DateVar = DATEADD(d,1,@DateVar)
END