用户自定义函数

来源:互联网 发布:淘宝论坛taoxiaobai 编辑:程序博客网 时间:2024/06/05 20:32

标量值函数

create function 架构名.function_name(@传入变量1 变量_类型, @传入变量2 变量_类型......)returns return_date_typeasbegin    --declare the return variable here    declare @variable1 variable_type...    ...    --add the T-SQL statements to compute the return value here    --Return the result of function    return @..endgo

执行函数体

--方法一 select 架构名.functionName(..参数)--方法二 用executr关键字来执行标量值函数,此外还可以用于存储过程等,首先要申明一个用于保存输出的变量,然后execute来调用函数declare @val1 val_type;execute @val1 = 架构名.functionName @传入变量名 = '...'

修改函数的话

alter function functionName()//....后面就和创建的差不多啦

例子
//求 输入一个Employee的出生日期,求的他的年龄,用一个函数实现

create function dbo.GetEmployeeAge(@BirthDate datetime)returns int asbegin    declare @Age int    select @Age = datediff(Year, @BirthDate, GETDATE())    return @Ageendgoselect  dbo.GetEmployeeAge('3/23/1982')或者declare @Age int;exec @Age =  dbo.GetEmployeeAge @BirthDate='3/23/1982'

表值函数

create function 架构名.functionName (@传入参数 参数累心,....)returns tableas--function bodyreturn(select .....from......(where...))go

执行函数体

用select执行select * from 架构名.函数名(参数1,参数2....)

例子

使用student数据库中适当的表,创建一个自定义函数-xbxs,该函数可以根据输入的系部名称返回学生的学号,姓名和入学时间。
create function xbxs(@SdeptNo nvarchar(20))returns tableas    return (select Sno 学号, Sname 姓名, null 入学时间 from dbo.Student)goselect * from dbo.xbxs('CS')go
原创粉丝点击