WEB开发网
开发学院数据库MSSQL Server sql server函数介绍-日期类 阅读

sql server函数介绍-日期类

 2009-11-19 15:40:14 来源:WEB开发网   
核心提示:12、计算工作时间的函数if exists (select * from dbo.sysobjects where id = object_id(N'[tb_worktime]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)drop table

12、计算工作时间的函数

if exists (select * from dbo.sysobjects where id = object_id(N'[tb_worktime]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [tb_worktime]
GO

--定义工作时间表
CREATE TABLE tb_worktime(
ID    int identity(1,1) PRIMARY KEY,      --序号
time_start smalldatetime,              --工作的开始时间
time_end smalldatetime,              --工作的结束时间
worktime AS DATEDIFF(Minute,time_start,time_end) --工作时数(分钟)
)
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[f_WorkTime]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[f_WorkTime]
GO

--计算两个日期之间的工作时间
CREATE FUNCTION f_WorkTime(
@date_begin datetime, --计算的开始时间
@date_end datetime   --计算的结束时间
)RETURNS int
AS
BEGIN
DECLARE @worktime int
IF DATEDIFF(Day,@date_begin,@date_end)=0
SELECT @worktime=SUM(DATEDIFF(Minute,
CASE WHEN CONVERT(VARCHAR,@date_begin,108)>time_start
THEN CONVERT(VARCHAR,@date_begin,108)
ELSE time_start END,
CASE WHEN CONVERT(VARCHAR,@date_end,108)<time_end
THEN CONVERT(VARCHAR,@date_end,108)
ELSE time_end END))
FROM tb_worktime
WHERE time_end>CONVERT(VARCHAR,@date_begin,108)
AND time_start<CONVERT(VARCHAR,@date_end,108)
ELSE
SET @worktime
=(SELECT SUM(CASE
WHEN CONVERT(VARCHAR,@date_begin,108)>time_start
THEN DATEDIFF(Minute,CONVERT(VARCHAR,@date_begin,108),time_end)
ELSE worktime END)
FROM tb_worktime
WHERE time_end>CONVERT(VARCHAR,@date_begin,108))
+(SELECT SUM(CASE
WHEN CONVERT(VARCHAR,@date_end,108)<time_end
THEN DATEDIFF(Minute,time_start,CONVERT(VARCHAR,@date_end,108))
ELSE worktime END)
FROM tb_worktime
WHERE time_start<CONVERT(VARCHAR,@date_end,108))
+CASE
WHEN DATEDIFF(Day,@date_begin,@date_end)>1
THEN (DATEDIFF(Day,@date_begin,@date_end)-1)
*(SELECT SUM(worktime) FROM tb_worktime)
ELSE 0 END
RETURN(@worktime)
END

上一页  3 4 5 6 7 8 9 10 11  下一页

Tags:sql server 函数

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接