• 存储过程——存储过程与函数(四)


    • 函数的定义:

    于编程语言中的函数类似,sql server 用户定义函数是接受参数,执行操作(如复杂运算)并将操作结果以值的形式返回的例程。返回值可以是单个标量值或结果集。

    • 函数的优点:
    1. 允许模块化程序设计
    2. 执行速度快
    3. 减少网络流量
    • 函数分类
    1. 系统函数
    2. 用户自定义函数
    • 标量函数
    • 表值函数

    上面说了这么多理论化的东西,下面介绍一个例子来说明:

     创建一个根据产品类型来查询产品信息的函数(表值函数)

    -- =============================================
    -- 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

    以上是个人总结部分,由不太详细指出,希望大家指出,本人将继续改进,提交代码质量,文章可读性...

  • 相关阅读:
    [hosts]在hosts中屏蔽一级域名和二级域名的写法
    [oracle]查询一个表中数据的插入时间
    [Windows Doc]微软官方文档
    [PL]如果天空是黑暗的,那就摸黑生存
    [LVM]创建LVM卷
    [powershell]获取FCID&Port
    [oracle]解决ora-01034 oracle not available
    [GoogleBlog]new-approach-to-china
    [时钟]配置日期时间并同步到硬件
    [rhel]安装oracle11g
  • 原文地址:https://www.cnblogs.com/tuqun/p/3657684.html
Copyright © 2020-2023  润新知