现在的位置: 首页 > 综合 > 正文

在MSSQL中使用CLR存储过程

2013年10月10日 ⁄ 综合 ⁄ 共 2183字 ⁄ 字号 评论关闭

前几日,我们在讨论mssql的T-SQL的函数集时,说到它远不够oracle的强大,连个字符串分隔函数都没有,都要自己写函数和存储过程实现。当时我就想,如果网上有人开展一个针对T-SQL,集合一些如字符穿扩展之类的函数类库,一定很受欢迎,在百了一下和G了一下我有点失望,我想要基本找不到,但SQL 2005的一个特性却进入我的眼帘,就是在SQL Server中调用CLR的存储过程,感觉就像以前在Oracle中调用Java的存储过程一样,如果这样不就可以把公用存储过程和函数做成类库,然后部署的时候直接合成到SQL中执行,这样编写逻辑处理就方便多了 ^_^

Let‘s go!下面我们来编写一个简单的字符串分隔存储过程来测试一下 o(∩_∩)o

 

程序集代码:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Data.SqlTypes;
  5. using System.Data.SqlClient;
  6. using System.Data;
  7. using Microsoft.SqlServer.Server;
  8. namespace TestCLR
  9. {
  10.     public class StringOperator
  11.     {
  12.         /// <summary>
  13.         /// Split string by Symbol
  14.         /// </summary>
  15.         /// <param name="RealWith">Source String</param>
  16.         /// <param name="Symbol">Split Symbol</param>
  17.         [Microsoft.SqlServer.Server.SqlProcedure]   
  18.         public static void Split(SqlString RealWith,SqlString Symbol)
  19.         {
  20.             string strRealWith = RealWith.ToString();
  21.             char[] chrSymbol = Symbol.ToString().ToCharArray();
  22.             string[] strReturn = strRealWith.Split(chrSymbol[0]);
  23.             SqlDataRecord record = new SqlDataRecord(
  24.                 new SqlMetaData("Column", SqlDbType.NVarChar, 4000));
  25.             // Mark the begining of the result-set.
  26.             SqlContext.Pipe.SendResultsStart(record);
  27.             // Send 10 rows back to the client.
  28.             for (int i = 0; i < strReturn.Length; i++)
  29.             {
  30.                 // Set values for each column in the row.
  31.                 record.SetString(0, strReturn[i]);
  32.                 // Send the row back to the client.
  33.                 SqlContext.Pipe.SendResultsRow(record);
  34.             }
  35.             // Mark the end of the result-set.
  36.             SqlContext.Pipe.SendResultsEnd();
  37.         }
  38.     }
  39. }

编译后,把程序集加进数据库中

 

 

 

记得把权限也加上 ^_^

 

 

然后设置数据库使用CLR

  1. -- 设置使用CLR
  2. exec sp_configure 'show advanced options''1';
  3. go
  4. reconfigure;
  5. go
  6. exec sp_configure 'clr enabled''1'
  7. go
  8. reconfigure;
  9. exec sp_configure 'show advanced options''1';
  10. go 

创建存储过程接口

  1. -- 创建存储过程
  2. CREATE PROCEDURE [dbo].[Split]
  3.     @RealWith [nvarchar](MAX), -- 参数列表
  4.     @Symbol [nvarchar](1)
  5. WITH EXECUTE AS CALLER
  6. AS
  7. EXTERNAL NAME [TestCLR].[TestCLR.StringOperator].[Split]

测试一下

  1. -- 测试
  2. EXEC dbo.Split N'甘都得,得左',N',';

结果出来了,是不是很方便,赶紧爽一把吧 ^_^

 

抱歉!评论已关闭.