Home >Database >Mysql Tutorial >MSSQL 计算两个日期相差的工作天数的语句

MSSQL 计算两个日期相差的工作天数的语句

WBOY
WBOYOriginal
2016-06-07 17:59:261043browse

MSSQL计算两个日期相差的工作天数的代码,需要的朋友可以参考下。

代码如下:
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
--计算两个日期相差的工作天数
CREATE FUNCTION f_WorkDay(
@dt_begin datetime, --计算的开始日期
@dt_end datetime --计算的结束日期
)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 numberelse
insert @t select dateadd(dd,number,@dt_begin) from master..spt_values
where numberreturn(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 個資料列受到影響)
*/
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
--计算两个日期相差的工作天数
CREATE FUNCTION f_WorkDay(
@dt_begin datetime, --计算的开始日期
@dt_end datetime --计算的结束日期
)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_beginBEGIN
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
*/
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn