Sql Server创建函数

在使用数据库的过程中,往往我们需要对有的数据先进行计算,然后再查询出来,所以我们就需要创建函数来完成这项任务。

创建的函数一般有两种返回类型,一种是返回一个集合(数据表),另一种是直接返回一个字符串。

下面是两种函数的创建实例

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(@onTime, @offTime)

    Return
END
--在存储过程中调用所创建的函数
Select * From dbo.fn_selectWorkTime(@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)
原文地址:https://www.cnblogs.com/970119449blog/p/8335239.html