以下是我在两个日期之间设置工作日的存储过程
Create procedure [dbo].[sp_workingdays](@startdate date,@enddate date,@createddatetime datetime,@adminid int)
as
declare @start date,@end date
declare @day varchar(50)
declare @timeid int
declare @daypare int
declare @workingdaytype varchar(20)
begin
set @start=@startdate
set @end=@enddate
while (@start<=@end)
begin
if @start not in (select Date from Generalholyday_details)
begin
select @day= DATENAME(dw,@start)
select @workingdaytype =case (DATEPART(DW,@start)+@@DATEFIRST)%7 when 1 then 'Leave Day' when 2 then 'Full Day' when 3 then 'Full Day' when 4 then 'Full Day'when 5 then 'Full Day' when 6 then 'Full Day' when 0 then 'Half Day' end
select @timeid=Time_id from Workingdaytimesetting_details where Workingday_type=@workingdaytype
insert into Workingday_details(Working_date,working_day,Time_id) values(@start,@day,@timeid)
update Workingday_details set createddatetime=@createddatetime where createddatetime is null
update Workingday_details set adminid=@adminid where adminid is null
end
set @start=DATEADD(day,1,@start)
end
end
GO
在datepart第1行是星期日。但实际上当我运行存储过程时,我在星期六得到1。我怎么能在星期日设置1。在我以前的系统中,我在同一程序中得到1个星期天。
答案 0 :(得分:0)
查看SET DATEFIRST (Transact-SQL)
将一周的第一天设置为1到7之间的数字。
要查看SET DATEFIRST的当前设置,请使用@@ DATEFIRST 功能
SET DATEFIRST的设置在执行或运行时设置,而不是在 解析时间。
指定SET DATEFIRST对DATEDIFF没有影响。 DATEDIFF总是如此 使用星期日作为一周的第一天,以确保功能 确定性的。
答案 1 :(得分:0)
试试这个 -
SET DATEFIRST 7
在小型重构后再尝试此查询:
CREATE PROCEDURE [dbo].[sp_workingdays]
(
@startdate DATE
, @enddate DATE
, @createddatetime DATETIME
, @adminid INT
)
AS BEGIN
DECLARE
@start DATE
, @end DATE
, @day VARCHAR(50)
, @timeid INT
, @workingdaytype VARCHAR(20)
SELECT
@start = @startdate
, @end = @enddate
WHILE (@start <= @end) BEGIN
IF NOT EXISTS(
SELECT 1
FROM Generalholyday_details
WHERE @start = [Date]
) BEGIN
SELECT
@day = DATENAME(dw, @start)
, @workingdaytype =
CASE WHEN dt = 1 THEN 'Leave Day'
WHEN dt IN (2,3,4,5,6) THEN 'Full Day'
ELSE 'Half Day'
END
FROM (
SELECT dt = (DATEPART(DW, @start) + @@DATEFIRST) % 7
) t
SELECT @timeid = Time_id
FROM Workingdaytimesetting_details
WHERE Workingday_type = @workingdaytype
INSERT INTO Workingday_details (Working_date, working_day, Time_id)
VALUES (@start, @day, @timeid)
UPDATE Workingday_details
SET createddatetime = @createddatetime
WHERE createddatetime IS NULL
UPDATE Workingday_details
SET adminid = @adminid
WHERE adminid IS NULL
END
SET @start = DATEADD(DAY, 1, @start)
END
END
GO