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

来源:互联网 发布:三坐标编程培训 编辑:程序博客网 时间:2024/05/20 23:02

这次我主要介绍的是如何用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公共语言运行库确实好用。哈哈

 

原创粉丝点击