杨叔叔 发表于 2018-10-19 11:32:21

SQL自定义函数function-Ricky

  https://blog.csdn.net/qq_23833037/article/details/53170789
  https://www.cnblogs.com/youring2/p/4916400.html
  用户定义自定义函数像内置函数一样返回标量值,也可以将结果集用表格变量返回。
  sql函数必须有返回值。
  ps: 函数看成一个处理某些数据的功能,因有返回值,则在代码使用中,需要一个处理过的数据。
  可直接调用函数处理数据,返回数据给代码使用。
  标量函数:返回一个标量值。
  表格值函数{内联表格值函数、多表格值函数}:返回行集(即返回多个值)
  标量函数和表格值函数的区别在于 返回是标量值(单个数字或者单个数据),还是表格值(多个数据)
  1、标量函数
create funetion 函数名(参数)  
return 返回值数据类型
  

  

  
begin
  
SQL语句(必须有return 变量或值)
  
End
  

  
--Schemabinding :将函数绑定到它引用的对象上(注:函数一旦绑定,则不能删除、修改,除非删除绑定)
  测试数据:
USE   
GO
  
/****** Object:Table .    Script Date: 04/19/2018 17:01:31 ******/
  
SET ANSI_NULLS ON
  
GO
  
SET QUOTED_IDENTIFIER ON
  
GO
  
CREATE TABLE .(
  
NULL,
  
(10) NULL
  
) ON
  
GO
  插入数据:
INSERT INTO number(number,name)  
VALUES(123,'a'),
  
(222,'b'),
  
(333,'c'),
  
(323,'d')
  例子:
alter function SumRes(@sco nvarchar(20)) --函数名和参数  
returns real --返回real 值类型
  
-- real=float(24)
  
as
  
begin
  
declare @sum real
  
declare @code varchar(11)
  
set @code = @sco + '%'
  
select @sum = sum(number) from number where name like @code
  
return @sum --返回值
  
end
  引用自定义函数:
  (用户自定义函数返回值可放在局部变量中,用set select exec 赋值)
declare @sum1 real,@sum2 real,@sum3 real  
set @sum1 = dbo.SumRes('b')
  
select @sum2 = dbo.SumRes('b')
  
exec @sum3 = dbo.sumRes'b'
  
select @sum1 ,@sum2 ,@sum3

  实例2:
  下面的这个函数根据生日返回年龄:
create function dbo.calcAge(@birthday datetime)    --函数名和参数  
returns int    --返回值类型
  
as
  
begin
  
    declare @now datetime
  
    declare @age int
  
    set @now=getdate()
  

  
    set @age=YEAR(@now)-YEAR(@birthday)
  

  
    return @age    --返回值
  
end
print dbo.calcAge('2000-1-1')  执行这段脚本创建函数,创建成功之后,我们调用一下看看效果: 输出:15
  2、表格值函数
  a、内联表格值函数
  格式:
  create function 函数名(参数)
  returns table
  
  as
  return(一条SQL语句)
  例子:
create function tabcmess(@code nvarchar(50))  
returns table
  
as
  
return(select * from number where name = @code)
  调用和结果:

  b、多句表格值函数
  多表格值函数的定义:包含多条SQL语句,必须或者至少有一条给表格变量赋值!!!
  表格变量格式:
  returns @变量名(dt) table( 列定义 | 约束定义 )
  对表格变量中可以执行 select, insert, update, delete,
  但select into 和 insert 语句的结果集是从存储过程插入。
  格式:
  create function 函数名(参数)
  return@dttable(列的定义)
  
  as
  begin
  SQL语句
  end
  例子:
create function tabcmess_mul(@code nvarchar(50))  
returns @dt table(number int,name nchar(10))
  
as
  
begin
  
insert into @dt select number,name from number where name = @code
  
return
  
end
  调用和结果:

  3. 修改自定义函数
alter function tabcmess_mul(@code nvarchar(50))  
returns @dt table(number int,name nchar(10))
  
as
  
begin
  
insert into @dt select number,name from number where name = @code
  
return
  
end
4. 删除自定义函数
drop function tabcmess_mul

页: [1]
查看完整版本: SQL自定义函数function-Ricky