sql T_sql 关于CLR扩展函数的使用(2)

这次我主要介绍的是如何用CLR开发返回 表值函数

首先我们还是新建一个用户定义的函数类FunctionReturnTableClass.cs

代码如下:

using System;

using System.Data.Sql;

using Microsoft.SqlServer.Server;

using System.Collections;

using System.Data.SqlTypes;

using System.Diagnostics;

using System.Data.SqlClient;

using System.Collections.Generic;

using System.Data;

 

public class FunctionReturnTableClass

{

     //这个特性定义了一个sql表值函数,此函数返回的表的定义为:id nvarchar(100),proname nvarchar(100),InsertCount nvarchar(100)

     //Name指的是这个表值函数的方法名

    // FillRowMethodName指的是填充表的方法类(并且指定了填充这个表的行的方法是FillRow 方法)

    //注意这个方法返回的一定是一个IEnumerable类型的,并且为公开,静态,这个方法的入参就是sql函数的入参

 

    [SqlFunction(DataAccess = DataAccessKind.Read, Name = "F_test", FillRowMethodName = "fillRows",

        TableDefinition = "id nvarchar(100),proname nvarchar(100),InsertCount nvarchar(100)")]

    public static IEnumerable GetData()

    {

        IList<model> items = new List<model>();

        SqlConnection connection = new SqlConnection("context connection=true;");

        SqlDataAdapter sda = new SqlDataAdapter();

        sda.SelectCommand = new SqlCommand("select id,proname,InsertCount from instore ", connection);

        DataSet ds = new DataSet();

        sda.Fill(ds);

        DataTable dt=ds.Tables[0];

        foreach (DataRow dr in dt.Rows)

        {

            items.Add(new model(dr));

        }

        return items;

    }

    //填充返回表的行的方法,这个方法有一定的规定:

    //一定是空返回的void类型,并且入参的第一个必须为object,其后面的参数需要时ref类型,好像out类型也可以

    static void fillRows(object obj, ref SqlString id, ref SqlString proname, ref SqlString InsertCount)

    {

        if (null != obj)

        {

            model item = (model)obj;

            id = item.id;

            proname = item.proname;

            InsertCount = item.InsertCount;

        }

    }

 

    //实体类

    struct model

    {

        public readonly SqlString id;

        public readonly SqlString proname;

        public readonly SqlString InsertCount;

 

        public model(DataRow dr)

        {

            this.id = dr["id"].ToString();

            this.proname = dr["proname"].ToString();

            this.InsertCount = dr["InsertCount"].ToString();

        }

    }

}

 

 

编译部署完成后,我们会看到在表值函数那里多了一个F_test的函数方法,我们执行这个方法,看会出现什么效果。

 

select * from dbo.F_test()

 

如下图:

 

 

果然返回的是一个数据表,我发现CLR公共语言运行库确实好用。哈哈

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值