MSSQL calculates the statement _mssql of the number of working days that differ by two dates

Source: Internet
Author: User
Tags mssql
Copy Code code as follows:

if exists (SELECT * from dbo.sysobjects WHERE id = object_id (N ' [dbo].[ F_workday] and Xtype in (n ' FN ', n ' IF ', n ' TF '))
Drop function [dbo]. [F_workday]
Go
--Calculates the number of working days that differ by two dates
CREATE FUNCTION F_workday (
@dt_begin datetime,--the calculated start date
@dt_end datetime--The calculated end date
) RETURNS int
As
BEGIN
DECLARE @i int
Select @i=abs (DateDiff (DD, @dt_begin, @dt_end))
DECLARE @t table (dt datetime)
If @dt_begin > @dt_end
Insert @t Select DATEADD (Dd,number, @dt_end) from master. Spt_values
where number<=@i and type= ' P '
Else
Insert @t Select DATEADD (Dd,number, @dt_begin) from master. Spt_values
where number<=@i and type= ' P '
Return (SELECT COUNT (*) from @t where (datepart (WEEKDAY,DT) +@ @datefirst-1)%7 between 1 and 5)
End
Go
Select Dbo.f_workday (' 2009-10-10 ', ' 2009-10-1 ')
/*
-----------
7
(1 data columns are impacted)
*/
if exists (SELECT * from dbo.sysobjects WHERE id = object_id (N ' [dbo].[ F_workday] and Xtype in (n ' FN ', n ' IF ', n ' TF '))
Drop function [dbo]. [F_workday]
Go
--Calculates the number of working days that differ by two dates
CREATE FUNCTION F_workday (
@dt_begin datetime,--the calculated start date
@dt_end datetime--The calculated end date
) RETURNS int
As
BEGIN
DECLARE @workday int,@i int, @bz bit, @dt datetime
Set @workday =0
IF @dt_begin > @dt_end
SELECT @bz =1, @dt = @dt_begin, @dt_begin = @dt_end, @dt_end = @dt
ELSE
SET @bz =0
While @dt_begin <= @dt_end
BEGIN
SELECT @workday =case
When (@ @DATEFIRST +datepart (Weekday, @dt_begin)-1)%7 BETWEEN 1 and 5
THEN @workday +1 ELSE @workday End,
@dt_begin = @dt_begin +1
End
Return (case when @bz =1 then-@workday ELSE @workday end)
End
Go
Select Dbo.f_workday (' 2009-10-10 ', ' 2009-10-1 ')
/*
-----------
-7
*/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.