Copy codeThe Code is as follows:
If exists (select * from dbo. sysobjects where id = object_id (n' [dbo]. [f_getdate] ') and xtype in (n'fn', n'if', n'tf '))
Drop function [dbo]. [f_getdate]
GO
Create function [dbo]. [f_getdate]
(
@ Year int, -- the year to be queried
@ Bz bit -- @ bz = 0 query workday, @ bz = 1 query rest day, @ bz is null query all date
)
RETURNS @ re TABLE (Date datetime, Weekday nvarchar (3 ))
As
Begin
DECLARE @ tb TABLE (ID int, Date datetime)
Insert @ tb select number,
Dateadd (day, number, DATEADD (Year, @ YEAR-1900, '2017-1-1 '))
From master .. spt_values where type = 'p' and number between 0 and 366
Delete from @ tb WHERE Date> DATEADD (Year, @ YEAR-1900, '2017-12-31 ')
IF @ bz = 0
Insert into @ re (Date, Weekday)
SELECT Date, DATENAME (Weekday, Date)
FROM @ tb
WHERE (DATEPART (Weekday, Date) + @ DATEFIRST-1) % 7 BETWEEN 1 AND 5
Else if @ bz = 1
Insert into @ re (Date, Weekday)
SELECT Date, DATENAME (Weekday, Date)
FROM @ tb
WHERE (DATEPART (Weekday, Date) + @ DATEFIRST-1) % 7 IN (0, 6)
ELSE
Insert into @ re (Date, Weekday)
SELECT Date, DATENAME (Weekday, Date)
FROM @ tb
RETURN
End
Go
Select * from dbo. [f_getdate] ('20140901', 0)