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 [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
- ››sql server自动生成批量执行SQL脚本的批处理
- ››sql server 2008亿万数据性能优化
- ››SQL Server 2008清空数据库日志方法
- ››sqlserver安装和简单的使用
- ››SQL Sever 2008 R2 数据库管理
- ››SQL SERVER无法安装成功,sqlstp.log文件提示[未发...
- ››Sql Server中通过父记录查找出所有关联的子记录
- ››SqlServer触发器、存储过程和函数
- ››SQL Server 中的事务(含义,属性,管理)
- ››Sqlite数据库插入和读取图片数据
- ››Sql server 2005拒绝了对对象 'xx表' (数...
- ››Sql server 2005拒绝了对对象 'xx表' (数...
更多精彩
赞助商链接