于编程语言中的函数类似,sql server 用户定义函数是接受参数,执行操作(如复杂运算)并将操作结果以值的形式返回的例程。返回值可以是单个标量值或结果集。
上面说了这么多理论化的东西,下面介绍一个例子来说明:
创建一个根据产品类型来查询产品信息的函数(表值函数)
-- ============================================= -- Author: <Author,,Name> -- Create date: 2014-04-11 21:10:42 -- Description: 根据产品类型查询产品 -- ============================================= CREATE FUNCTION [dbo].[FN_getproductbyCondition] ( -- Add the parameters for the function here @condition nvarchar(200) ) RETURNS TABLE AS RETURN ( select * from product where Type=@condition )
调用函数如下:
select * FROM FN_getproductbyCondition(2) --实际上等同于 select * from [dbo].[product] where Type=2
标量函数建立
CREATE FUNCTION FN_getproducttypebyId ( -- Add the parameters for the function here @typeid int ) RETURNS nvarchar(50) AS BEGIN -- Declare the return variable here --返回值 DECLARE @typeName nvarchar(50) -- Add the T-SQL statements to compute the return value here --执行sql语句 SELECT @typeName=Name from [dbo].[productType] where id=@typeid -- Return the result of the function --返回结果 RETURN @typeName END GO
标量函数调用
--测试标量函数 SELECT [ID] ,[Name] ,[Price] ,[Address] ,[Type]=dbo.FN_getproducttypebyId(Type) FROM [wisdominfo].[dbo].[product]
上述调用函数类似于调用了联合查询,或子查询
CREATE PROCEDURE GetProinfo AS BEGIN SELECT [ID] ,[Name] ,[Price] ,[Address] ,[Type] ,TypeName=dbo.FN_getproducttypebyId(Type) FROM [wisdominfo].[dbo].[product] END GO
以上是个人总结部分,由不太详细指出,希望大家指出,本人将继续改进,提交代码质量,文章可读性...
存储过程——存储过程与函数(四),布布扣,bubuko.com
原文:http://www.cnblogs.com/tuqun/p/3657684.html