前几日,我们在讨论mssql的T-SQL的函数集时,说到它远不够oracle的强大,连个字符串分隔函数都没有,都要自己写函数和存储过程实现。当时我就想,如果网上有人开展一个针对T-SQL,集合一些如字符穿扩展之类的函数类库,一定很受欢迎,在百了一下和G了一下我有点失望,我想要基本找不到,但SQL 2005的一个特性却进入我的眼帘,就是在SQL Server中调用CLR的存储过程,感觉就像以前在Oracle中调用Java的存储过程一样,如果这样不就可以把公用存储过程和函数做成类库,然后部署的时候直接合成到SQL中执行,这样编写逻辑处理就方便多了 ^_^
Let‘s go!下面我们来编写一个简单的字符串分隔存储过程来测试一下 o(∩_∩)o
程序集代码:
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Data.SqlTypes;
- using System.Data.SqlClient;
- using System.Data;
- using Microsoft.SqlServer.Server;
- namespace TestCLR
- {
- public class StringOperator
- {
- /// <summary>
- /// Split string by Symbol
- /// </summary>
- /// <param name="RealWith">Source String</param>
- /// <param name="Symbol">Split Symbol</param>
- [Microsoft.SqlServer.Server.SqlProcedure]
- public static void Split(SqlString RealWith,SqlString Symbol)
- {
- string strRealWith = RealWith.ToString();
- char[] chrSymbol = Symbol.ToString().ToCharArray();
- string[] strReturn = strRealWith.Split(chrSymbol[0]);
- SqlDataRecord record = new SqlDataRecord(
- new SqlMetaData("Column", SqlDbType.NVarChar, 4000));
- // Mark the begining of the result-set.
- SqlContext.Pipe.SendResultsStart(record);
- // Send 10 rows back to the client.
- for (int i = 0; i < strReturn.Length; i++)
- {
- // Set values for each column in the row.
- record.SetString(0, strReturn[i]);
- // Send the row back to the client.
- SqlContext.Pipe.SendResultsRow(record);
- }
- // Mark the end of the result-set.
- SqlContext.Pipe.SendResultsEnd();
- }
- }
- }
编译后,把程序集加进数据库中
记得把权限也加上 ^_^
然后设置数据库使用CLR
- -- 设置使用CLR
- exec sp_configure 'show advanced options', '1';
- go
- reconfigure;
- go
- exec sp_configure 'clr enabled', '1'
- go
- reconfigure;
- exec sp_configure 'show advanced options', '1';
- go
创建存储过程接口
- -- 创建存储过程
- CREATE PROCEDURE [dbo].[Split]
- @RealWith [nvarchar](MAX), -- 参数列表
- @Symbol [nvarchar](1)
- WITH EXECUTE AS CALLER
- AS
- EXTERNAL NAME [TestCLR].[TestCLR.StringOperator].[Split]
测试一下
- -- 测试
- EXEC dbo.Split N'甘都得,得左',N',';
结果出来了,是不是很方便,赶紧爽一把吧 ^_^