T-SQL之自定义函数

用户自定义函数分标量函数、表值函数、内嵌表值函数

一、标量函数

CREATE  FUNCTION  函数名([形式参数名称 [as] 数据类型[=default] [,…n] ]) --形参可有多个
RETURNS  返回数据类型
[with encryption]
[AS]
BEGIN
   函数内容                   --可没有函数体
    RETURN  表达式     --必须要有返回值语句
END      

例如:

create function myfun1(@dept char(10),@menshu int)
returns int
begin
 declare @renshu int
 select @renshu=count(sc.sno) from student,sc
 where student.sno=sc.sno and ssex='M' and sdept=@dept
 group by sc.sno
 having count(cno)>@menshu
 return @renshu
end

调用:select '学生人数'=dbo.myfun1('SC',1)

二、表值函数

CREATE  FUNCTION  函数名([形式参数名称 [AS] 数据类型 [=default] [,…n] ])
RETURNS  @return_variable    Table  <table_definition>
[AS]   --@return_variable 是临时表的名称,要加@符号
begin
    function_body   --在这里将查询结果保存到表 
                   --@return_variable中,如insert into ... Select  
    RETURN
end

三、内嵌表值函数

CREATE  FUNCTION  函数名([形式参数名称 [AS]  数据类型 [=default] [,…n] ])
RETURNS  Table
[with encryption]
[AS]
--没有begin..end(否则有语法),只有一条return语句;
      RETURN  (select语句)

原文地址:https://www.cnblogs.com/mymindview/p/3451259.html