Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
573 views
in Technique[技术] by (71.8m points)

sql server - SET DATEFIRST in FUNCTION

I want to SET DATEFIRST in my function but it is not allowed.

SET DATEFIRST 1

I can add the code in a SP and call the SP from the function but I am not keen on doing that.

I can SET the DATEFIRST before I call my function but I am not keen on doing that as well.

Any other work around?

EDIT

Below is the code I want to use in my FUNCTION to return the total working days of the month. But I cant add this code into the FUNCTION because of my DATEFIRST

DECLARE @my int
DECLARE @myDeduct int
DECLARE @day INT
DECLARE @mydate DATETIME
DECLARE @TotalDays INT

SET @mydate = GETDATE()

SET @myDeduct = 0
IF (@@DATEFIRST + DATEPART(DW, @mydate)) % 7 not in (0,1)
SET DateFirst 1 -- Set it monday=1 (value)

--Saturday and Sunday on the first and last day of a month will Deduct 1
IF (DATEPART(weekday,(DATEADD(dd,-(DAY(@mydate)-1),@mydate))) > 5)
SET @myDeduct = @myDeduct + 1

IF (DATEPART(weekday,(DATEADD(dd,-(DAY(DATEADD(mm,1,@mydate))),DATEADD(mm,1,@mydate)))) > 5)
SET @myDeduct = @myDeduct + 1

SET @my = day(DATEADD(dd,-(DAY(DATEADD(mm,1,@mydate))),DATEADD(mm,1,@mydate)))

Set @TotalDays = (select (((@my/7) * 5 + (@my%7)) - @myDeduct))

Select @TotalDays
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Instead of

SET DATEFIRST 1

You can do

SELECT (DATEPART(weekday, GETDATE()) + @@DATEFIRST - 2) % 7 + 1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...