在使用数据库的过程中,往往我们需要对有的数据先进行计算,然后再查询出来,所以我们就需要创建函数来完成这项任务,在数据库的Programmability(如图1)下面的Function中创建函数(如图2)
(图1)(图2)
在这里创建的函数一般有两种返回类型,一种是返回一个集合(数据表),另一种是直接返回一个字符串(如图3)
(图3)
下面是两种函数的创建实例
1、集合
创建函数fn_selectWorkTime
Create FUNCTION fn_selectWorkTime
(
@plantID int
, @CheckTime datetime --考勤时间
, @deptID int --部门
, @wShop int --工段
, @roleID int --岗位
, @wGroup int --班组
, @uID int --员工
)
RETURNS @retValue Table (atWork datetime, offWork datetime)
AS
BEGIN
Declare @onTime datetime
, @offTime datetime
--......
Set @onTime = '2016-07-01 08:00'
Set @offTime = '2016-07-01 17:00'
Insert Into @retValue(atWork, offWork)
Values(@onTime1, @offTime1, @isSunday, @atDinner, @offDinner, @atLunch, @offLunch, @hasStdTime)
Return
END
在存储过程中调用所创建的函数
Select *
From dbo.fn_calStdAttAll(@plantid, @time1, @deptID, @wShop, @roleID, @wGroup, @uid5)
2、字符串
创建函数 fn_calStdAtt
CREATE FUNCTION fn_calStdAtt
(
@CheckTime datetime --考勤时间
, @deptID int --部门
, @wShop int --工段
, @roleID int --岗位
, @wGroup int --班组
, @uID int --员工
, @which char(1) --I:上班时间,O:下班时间
)
RETURNS varchar(20)
AS
BEGIN
Declare @retValue datetime
--......
Set @retValue = '2016-07-01 08:00'
Return Convert(varchar(20), @retValue, 120)
END
在存储过程中调用所创建的函数
select dbo.fn_calStdAtt (@CheckTime, @deptID, @wShop, @roleID, @wGroup, @uID, @which)
以上只是个人在开发中的总结,不足之处望大家多指教
原标题:Sql Server创建函数
关键词:sql