Home Database Mysql Tutorial 用程序集编写clr表值函数:把正则表达式引入数据库中

用程序集编写clr表值函数:把正则表达式引入数据库中

Jun 07, 2016 pm 03:05 PM
function introduce database regular program write expression

正则表达式非常好,但在数据库中就是没有,但可以通过程序集方式扩展 先编写一个dll,标量函数很好写,表值函数麻烦一点 下面是C#代码 using System; using System.Data; using System.Data.SqlClient; using System.Data.SqlTypes; using Microsoft.SqlServ

正则表达式非常好,但在数据库中就是没有,但可以通过程序集方式扩展

先编写一个dll,标量函数很好写,表值函数麻烦一点

下面是C#代码

<span>using</span><span> System;
</span><span>using</span><span> System.Data;
</span><span>using</span><span> System.Data.SqlClient;
</span><span>using</span><span> System.Data.SqlTypes;
</span><span>using</span><span> Microsoft.SqlServer.Server;
</span><span>using</span><span> System.Text.RegularExpressions;
</span><span>using</span><span> System.Collections;
</span><span>public</span> <span>partial</span> <span>class</span><span> RegExpFunctions
{</span>
Copy after login

    [SqlFunction(
      DataAccess = DataAccessKind.Read,
      FillRowMethodName = "MatchsFun_FillRow",
      TableDefinition = "pos int,match NVARCHAR(500)")]
    public static IEnumerable MatchsFun(string input, string patten)
    {
      MatchCollection mc;
      Regex r = new Regex(patten);
      mc = r.Matches(input);
      return mc;
    }

Copy after login

    public static void MatchsFun_FillRow(object mc,out int pos,out SqlString sqlmatch)
    {
      Match it = (Match)mc;
      pos = it.Index;
      sqlmatch = it.Value;
    }

};

程序集名称是RegulerExp2

代码中有几点解释一下:

(1)表值函数必须是IEnumerable,简单讲是必须有这个接口的类,MatchCollection就具有这个接口;

(2)必须提供一个回调函数,在函数属性FillRowMethodName = "MatchsFun_FillRow"中指明,这个函数负责填充数据,

    public static void MatchsFun_FillRow(object mc,out int pos,out SqlString sqlmatch)
    {
      Match it = (Match)mc;
      pos = it.Index;
      sqlmatch = it.Value;
    }

这里的object mc是什么呢?

我们可以想象一下遍历

foreach (Match it in mc)
{  
}

这里的object mc就是foreach里的Match it。

然后数据库把out int pos,out SqlString sqlmatch这两个量取出去放进表里。

 

下一步是添加程序集

第一步是把数据库的clr打开,不细说,自己网上查

第二步添加程序集

用程序集编写clr表值函数:把正则表达式引入数据库中

第三步,写一个数据库表值函数包装

<span>create</span> <span>FUNCTION</span> <span>[</span><span>dbo</span><span>]</span>.<span>[</span><span>MatchList</span><span>]</span>(<span>@input</span> <span>[</span><span>nvarchar</span><span>]</span>(<span>1000</span>), <span>@patten</span> <span>[</span><span>nvarchar</span><span>]</span>(<span>1000</span><span>))
</span><span>RETURNS</span>  <span>TABLE</span><span> (
    pos </span><span>int</span>,<span>[</span><span>match</span><span>]</span> <span>[</span><span>nvarchar</span><span>]</span>(<span>500</span>) <span>NULL</span><span>
) </span><span>WITH</span> <span>EXECUTE</span> <span>AS</span><span> CALLER
</span><span>AS</span><span> 
EXTERNAL NAME </span><span>[</span><span>RegulerExp2</span><span>]</span>.<span>[</span><span>RegExpFunctions</span><span>]</span>.<span>[</span><span>MatchsFun</span><span>]</span>
Copy after login

 

可以了。

前面写了一个小示例,大家好像没兴趣,写一个实用点的例子吧。数据库中没有split函数,用正则表达式就很容易了

<span>select</span> match <span>from</span> dbo.MatchList(<span>'</span><span>1,2,4,12,24,41</span><span>'</span>,<span>'</span><span>(?<span>'</span>)</span>
Copy after login

 

结果为

用程序集编写clr表值函数:把正则表达式引入数据库中

 

如果以一个存储过程方式

C#代码为

<span>[Microsoft.SqlServer.Server.SqlProcedure]
    </span><span>public</span> <span>static</span> <span>void</span> Matches(<span>string</span> input, <span>string</span><span> patten)
    {
        </span><span>//</span><span>像构造Table一样来构造SqlDataRecord,其中SqlMetaData类似DataColumn</span>
        SqlDataRecord dataRecord = <span>new</span> SqlDataRecord(<span>new</span><span> SqlMetaData[] {                
                </span><span>new</span> SqlMetaData(<span>"</span><span>ID</span><span>"</span><span>, SqlDbType.Int),
                </span><span>new</span> SqlMetaData(<span>"</span><span>index</span><span>"</span><span>, SqlDbType.Int),
                </span><span>new</span> SqlMetaData(<span>"</span><span>match</span><span>"</span>, SqlDbType.NVarChar,<span>100</span><span>)
                    });
        </span><span>//</span><span>开始填充</span>
<span>        SqlContext.Pipe.SendResultsStart(dataRecord);

        MatchCollection mc;
        Regex r </span>= <span>new</span><span> Regex(patten);
        mc </span>=<span> r.Matches(input);
        </span><span>for</span> (<span>int</span> i = <span>0</span>; i )
        {            
            <span>//</span><span>SqlDataRecord.SetString类似DataRow的功能,像Table中填充值</span>
            dataRecord.SetInt32(<span>0</span><span>, i);
            dataRecord.SetInt32(</span><span>1</span><span>, mc[i].Index);
            dataRecord.SetString(</span><span>2</span><span>,  mc[i].Value);
            </span><span>//</span><span>通过SendResultsRow把数据填充到Table,相关于Table.Rows.Add(DataRow);</span>
<span>            SqlContext.Pipe.SendResultsRow(dataRecord);
        }

        
        </span><span>//</span><span>填充结束,返回结果集</span>
<span>        SqlContext.Pipe.SendResultsEnd();
    }</span>
Copy after login

数据库端写一个存储过程包装

<span>CREATE</span> <span>PROCEDURE</span> <span>[</span><span>dbo</span><span>]</span>.<span>[</span><span>Macths</span><span>]</span>
    <span>@input</span> <span>[</span><span>nvarchar</span><span>]</span>(<span>1000</span><span>),
    </span><span>@patten</span> <span>[</span><span>nvarchar</span><span>]</span>(<span>1000</span><span>)
</span><span>WITH</span> <span>EXECUTE</span> <span>AS</span><span> CALLER
</span><span>AS</span><span>
EXTERNAL NAME </span><span>[</span><span>RegulerExp</span><span>]</span>.<span>[</span><span>RegulerExp</span><span>]</span>.<span>[</span><span>Matches</span><span>]</span>
Copy after login

别的一样

运行

<span>exec</span> dbo.Macths <span>'</span><span>1,2,4,12,24,41</span><span>'</span>,<span>'</span><span>(?<span>'</span></span>
Copy after login

 

结果为

用程序集编写clr表值函数:把正则表达式引入数据库中

 

其他标量函数很简单,自己百度,类似

 

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos Jul 18, 2024 am 05:48 AM

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

How to match multiple words or strings using Golang regular expression? How to match multiple words or strings using Golang regular expression? May 31, 2024 am 10:32 AM

Golang regular expressions use the pipe character | to match multiple words or strings, separating each option as a logical OR expression. For example: matches "fox" or "dog": fox|dog matches "quick", "brown" or "lazy": (quick|brown|lazy) matches "Go", "Python" or "Java": Go|Python |Java matches words or 4-digit zip codes: ([a-zA

Complete collection of excel function formulas Complete collection of excel function formulas May 07, 2024 pm 12:04 PM

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

How to handle database connection errors in PHP How to handle database connection errors in PHP Jun 05, 2024 pm 02:16 PM

To handle database connection errors in PHP, you can use the following steps: Use mysqli_connect_errno() to obtain the error code. Use mysqli_connect_error() to get the error message. By capturing and logging these error messages, database connection issues can be easily identified and resolved, ensuring the smooth running of your application.

Detailed tutorial on establishing a database connection using MySQLi in PHP Detailed tutorial on establishing a database connection using MySQLi in PHP Jun 04, 2024 pm 01:42 PM

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

Things to note when Golang functions receive map parameters Things to note when Golang functions receive map parameters Jun 04, 2024 am 10:31 AM

When passing a map to a function in Go, a copy will be created by default, and modifications to the copy will not affect the original map. If you need to modify the original map, you can pass it through a pointer. Empty maps need to be handled with care, because they are technically nil pointers, and passing an empty map to a function that expects a non-empty map will cause an error.

How to save JSON data to database in Golang? How to save JSON data to database in Golang? Jun 06, 2024 am 11:24 AM

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

How to use database callback functions in Golang? How to use database callback functions in Golang? Jun 03, 2024 pm 02:20 PM

Using the database callback function in Golang can achieve: executing custom code after the specified database operation is completed. Add custom behavior through separate functions without writing additional code. Callback functions are available for insert, update, delete, and query operations. You must use the sql.Exec, sql.QueryRow, or sql.Query function to use the callback function.

See all articles