提高你的数据库编程效率:Microsoft CLR Via Sql Server
你还在为数据库编程而抓狂吗?那些恶心的脚本拼接,低效的脚本调试的日子将会与我们越来越远啦。现在我们能用支持.NET的语言来开发数据库中的对象,如:存储过程,函数,触发器,集合函数已及复杂的类型。看到这些你还能淡定吗?哈哈,不仅仅是这些。那些能被.NET支持的第三方扩展通过该技术统统都能应用在数据库编程上,如:正则表达式,.NET庞大的加密解密库,以及各种.NET集成的排序和搜索算法。
下面我就来一一介绍怎么使用该技术来解放我们的双手!
实现存储过程
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using Microsoft.SqlServer.Server;
- using System.Data;
- using System.Data.SqlClient;
- using System.Data.SqlTypes;
- using System.Collections;
- public class SampleStoreProcedure
- {
- [SqlProcedure]
- public static void PrintStudentDetail()
- {
- SqlConnection conn = new SqlConnection("Context connection=true");
- conn.Open();
- SqlCommand cmd = new SqlCommand("select * from student", conn);
- SqlCommand cmd2 = new SqlCommand("insert into studentdetail values(@detail)");
- SqlDataReader reader;
- string tmpData=string.Empty;
- ArrayList tmpDataArray=new ArrayList();
- reader = cmd.ExecuteReader();
- while (reader.Read())
- {
- for (int i = 0; i < reader.FieldCount; i++)
- {
- tmpData += reader[i].ToString();
- }
- tmpDataArray.Add(tmpData);
- }
- reader.Close();
- cmd2.Connection = conn;
- foreach (string tmp in tmpDataArray)
- {
- cmd2.Parameters.Clear();
- cmd2.Parameters.AddWithValue("@detail", tmp);
- cmd2.ExecuteNonQuery();
- }
- conn.Close();
- //conn2.Close();
- }
- [SqlProcedure]
- public static void GetStudentDetail(int id)
- {
- SqlConnection conn = new SqlConnection("Context connection=true");
- SqlCommand cmd = new SqlCommand("select * from student where id=@id", conn);
- SqlDataReader reader;
- cmd.Parameters.AddWithValue("@id", id);
- try
- {
- conn.Open();
- reader = cmd.ExecuteReader();
- SqlPipe pipe = SqlContext.Pipe;
- pipe.Send(reader);
- reader.Close();
- }
- catch
- {
- conn.Close();
- }
- finally
- {
- }
- }
- };
部署步骤
- 1.编译项目,获取生成的DLL文件。
- 2.在数据库中输入命令sp_configure [clr enabled],1 reconfigure --开启对程序集的信任权限。
- 3.输入命令:create assembly chapter34_UDT from 'c:\chapter34_UDT.dll' 注册程序集
- 4.输入命令:
- <p>--注册存储过程
- create procedure PrintStudentDetail
- as
- external name chapter34_UDT.SampleStoreProcedure.PrintStudentDetail</p><p>--注册带参数的存储过程
- create procedure GetStudentDetail
- (
- @Id int
- )
- as
- external name chapter34_UDT.SampleStoreProcedure.GetStudentDetail</p>
执行结果
- exec PrintStudentDetail
- exec GetStudentDetail 1
存储过程PrintStudentDetail执行结果
存储过程GetStudentDetail执行的结果
实现函数
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Data;
- using System.Data.SqlClient;
- using System.Data.SqlTypes;
- using Microsoft.SqlServer.Server;
- using System.Security;
- using System.Security.Cryptography;
- public class SampleFunction
- {
- public SampleFunction()
- {
- }
- [SqlFunction]
- public static SqlString Hash(SqlString data)
- {
- SHA1 sha1 = SHA1.Create();
- byte[] tmp = Encoding.ASCII.GetBytes(data.Value);
- string result= Convert.ToBase64String(sha1.ComputeHash(tmp));
- return new SqlString(result);
- }
- }
部署步骤
- 1.编译项目,获取生成的DLL文件。
- 2.在数据库中输入命令:
- sp_configure [clr enabled],1 reconfigure --开启对程序集的信任权限。
- 3.输入命令:
- create assembly chapter34_UDT from 'c:\chapter34_UDT.dll' 注册程序集
- --如果上述步骤已经做了就忽略
- <p>4.输入命令:</p>
- --注册函数
- create function HashSomeThing(@data nvarchar) returns nvarchar
- as
- external name chapter34_UDT.SampleFunction.[Hash]
执行结果
- <p>输入调用命令:</p>select dbo.HashSomeThing(name) from Student
实现表值函数
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Data;
- using System.Data.SqlClient;
- using System.Data.SqlTypes;
- using Microsoft.SqlServer.Server;
- using System.Text.RegularExpressions;
- using System.Xml.Linq;
- using System.Xml;
- using System.IO;
- using System.Collections;
- public class SampleTableValueFunction
- {
- ///
- /// 表值函数的主体,该函数需要结合“内容填充函数”才能发挥功能。这里的“内容填充函数”是通过
- /// 属性“FillRowMethodName”属性来指定的。属性“TableDefinition”用来定义返回表格的格式。
- ///
- [SqlFunction(TableDefinition = "tmp_value nvarchar(max)", FillRowMethodName = "FillRow")]
- public static IEnumerable PrintOneToTen()
- {
- IList<string> result2 = new List<string>();
- var matches = new string[]{
- "one",
- "two",
- "three",
- "four",
- "five",
- "six",
- "seven",
- "eight",
- "nine",
- "ten"
- };
- return matches.AsEnumerable();
- }
- public static void FillRow(object obj, out SqlString tmp)
- {
- tmp = new SqlString(obj.ToString());
- }
- }
部署步骤
- 1.编译项目,获取生成的DLL文件。
- 2.在数据库中输入命令:
- sp_configure [clr enabled],1 reconfigure --开启对程序集的信任权限。
- 3.输入命令:
- create assembly chapter34_UDT from 'c:\chapter34_UDT.dll' 注册程序集
- --如果上述步骤已经做了就忽略
- 4.输入命令:
- create function SampleTableValueFunction() returns table(tmp_value nvarchar(max) null)
- as
- external name chapter34_UDT.SampleTableValueFunction.PrintOneToTen
执行结果
实现触发器
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using Microsoft.SqlServer.Server;
- using System.Data;
- using System.Data.SqlClient;
- using System.Data.SqlTypes;
- public class SampleTrigger
- {
- public SampleTrigger()
- {
- }
- [SqlTrigger(Event = "For Insert,Update,Delete", Name = "PrintInfo", Target = "Student")]
- public static void PrintInfo()
- {
- SqlTriggerContext triggerContext = SqlContext.TriggerContext;
- SqlConnection conn = new SqlConnection("Context connection=true");
- SqlCommand cmd = new SqlCommand();
- cmd.Connection = conn;
- switch (triggerContext.TriggerAction)
- {
- case TriggerAction.Insert:
- cmd.CommandText = "insert into StudentDetail values('insert operation!')";
- break;
- case TriggerAction.Delete:
- cmd.CommandText = "insert into StudentDetail values('delete operation!')";
- break;
- case TriggerAction.Update:
- cmd.CommandText = "insert into StudentDetail values('update operation!')";
- break;
- default:
- break;
- }
- try
- {
- conn.Open();
- cmd.ExecuteNonQuery();
- }
- catch
- {
- }
- finally
- {
- conn.Close();
- }
- }
- [SqlTrigger(Name="InsertSomething",Target="chapter30.dbo.Student",Event="FOR INSERT")]
- public static void InsertSomething()
- {
- SqlTriggerContext triggerContext = SqlContext.TriggerContext;
- if (triggerContext.TriggerAction == TriggerAction.Insert)
- {
- var conn = new SqlConnection("Context connection=true");
- var cmd = new SqlCommand();
- cmd.Connection = conn;
- cmd.CommandText = "Insert into StudentDetail values('insert event')";
- conn.Open();
- cmd.ExecuteNonQuery();
- conn.Close();
- }
- }
- }
部署步骤
- 1.编译项目,获取生成的DLL文件。
- 2.在数据库中输入命令:
- sp_configure [clr enabled],1 reconfigure --开启对程序集的信任权限。
- 3.输入命令:
- create assembly chapter34_UDT from 'c:\chapter34_UDT.dll' 注册程序集
- --如果上述步骤已经做了就忽略
- 4.输入命令:
- --注册触发器
- create trigger PrintSomething on Student
- for insert,update,delete
- as
- external name chapter34_UDT.SampleTrigger.PrintInfo
执行结果
- 输入命令:
- insert into Student values(12345,'tmp','11','11')
- update Student set Name='new'+Name where Id=12345
- delete from Student where Id=12345
- select * from StudentDetail
实现聚合函数
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using Microsoft.SqlServer.Server;
- using System.Data;
- using System.Data.SqlClient;
- using System.Data.SqlTypes;
- [Serializable]
- [SqlUserDefinedAggregate(Format.Native)]
- public struct SampleSum
- {
- private int sum;
- public void Init()
- {
- sum = 0;
- }
- public void Accumulate(SqlInt32 Value)
- {
- sum += Value.Value;
- }
- public void Merge(SampleSum Group)
- {
- sum += Group.sum;
- }
- public SqlInt32 Terminate()
- {
- return new SqlInt32(sum);
- }
- }
部署步骤
- 1.编译项目,获取生成的DLL文件。
- 2.在数据库中输入命令:
- sp_configure [clr enabled],1 reconfigure --开启对程序集的信任权限。
- 3.输入命令:
- create assembly chapter34_UDT from 'c:\chapter34_UDT.dll' 注册程序集
- --如果上述步骤已经做了就忽略
- 4.输入命令:
- --注册聚合函数
- create aggregate SampleSum(@value int) returns int
- external name [chapter34_UDT].SampleSum
执行结果
- 输入命令:
- select dbo.SampleSum(TAggregate) from TAggregate
- select Sum(TAggregate) from TAggregate
实现类型
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using Microsoft.SqlServer.Server;
- using System.Data.SqlTypes;
- using System.Data;
- using System.Data.SqlClient;
- [Serializable]
- [Microsoft.SqlServer.Server.SqlUserDefinedType(Format.Native)]
- public struct Facade : INullable
- {
- public bool isNull;
- int hairColor;
- int tall;
- int skin;
- int country;
- public Facade(int hairColor, int tall, int skin, int country)
- {
- isNull = false;
- this.hairColor = hairColor;
- this.tall = tall;
- this.skin = skin;
- this.country = country;
- }
- public static Facade Null
- {
- get
- {
- return new Facade { isNull = true };
- }
- }
- public override string ToString()
- {
- StringBuilder sb = new StringBuilder();
- sb.AppendFormat("{0};", hairColor);
- sb.AppendFormat("{0};", tall);
- sb.AppendFormat("{0};", skin);
- sb.AppendFormat("{0}", country);
- return sb.ToString();
- }
- public static Facade Parse(SqlString data)
- {
- if (data.IsNull)
- {
- return new Facade { isNull = true };
- }
- Facade result;
- string[] tmpData = data.Value.Split(';');
- result = new Facade(int.Parse(tmpData[0]), int.Parse(tmpData[1]), int.Parse(tmpData[2]), int.Parse(tmpData[3]));
- return result;
- }
- public bool IsNull
- {
- get { return isNull; }
- }
- }
部署步骤
- 1.编译项目,获取生成的DLL文件。
- 2.在数据库中输入命令:
- sp_configure [clr enabled],1 reconfigure --开启对程序集的信任权限。
- 3.输入命令:
- create assembly chapter34_UDT from 'c:\chapter34_UDT.dll' 注册程序集
- --如果上述步骤已经做了就忽略
- 4.输入命令:
- create type Facade external name
- [chapter34_UDT].Facade
执行结果
小结
CLR Sql Server 的推出大大的提高了Sql Server的脚本编程效率问题,并且这项技术给了我们很大的相信空间。现在我们就来用有限的手段实现无限的可能吧!
reference from : http://blog.csdn.net/ghostbear/article/details/7333189
提高你的数据库编程效率:Microsoft CLR Via Sql Server的更多相关文章
- [转]如何将高版本的SQL Server数据库备份到低版本的SQL Server
本文转自:https://blog.csdn.net/wang465745776/article/details/54969676 前提条件备份SQL Server服务器版本为:12.0.2000.8 ...
- Excel VBA 连接各种数据库(三) VBA连接SQL Server数据库
本文主要涉及: VBA中的SQL Server环境配置 VBA连接SQL Server数据库 VBA读写SQL Server数据 如何安装SQL Client 系统环境: Windows 7 64bi ...
- 无法将数据库从SINGLE_USER模式切换回MULTI_USER模式(Error 5064),及查找SQL Server数据库中用户spid(非SQL Server系统spid)的方法
今天公司SQL Server数据库无意间变为SINGLE_USER模式了,而且使用如下语句切换回MULTI_USER失败: ALTER DATABASE [MyDB] SET MULTI_USER W ...
- 【数据库】一篇文章搞掂:SQL Server数据库
问题: 1.同一段代码,在存储过程中运行比普通SQL执行速度慢几十倍 原理: 在SQL Server中有一个叫做 “Parameter sniffing”参数嗅探的特性.SQL Server在存储过程 ...
- 用连接池提高Servlet访问数据库的效率
Java Servlet作为首选的服务器端数据处理技术,正在迅速取代CGI脚本.Servlet超越CGI的优势之一在于,不仅多个请求可以共享公用资源,而且还可以在不同用户请求之间保留持续数据.本文介绍 ...
- 数据库优化之锁表查询 (Sql Server)
查询锁表语句 select request_session_id spid,DB_NAME(resource_database_id) databaseName, OBJECT_NAME(resour ...
- App_Data 目录中的数据库位置指定了一个本地 SQL Server
<configuration> <system.web> <compilation debug="true" targetFramework=&quo ...
- 数据库获取前N条记录SQL Server与SQLite的区别
在使用sql语句进行前20条记录查询时SQL Server可以这样写: 1: select top 20 * from [table] order by ids desc 2: select top ...
- (在数据库中调用webservices。)SQL Server 阻止了对组件 'Ole Automation Procedures' 的 过程'sys.sp_OACreate' 的访问
--开启 Ole Automation Procedures sp_configure 'show advanced options', 1; GO RECONFIGURE; GO sp_config ...
随机推荐
- AC日记——字符替换 openjudge 1.7 08
08:字符替换 总时间限制: 1000ms 内存限制: 65536kB 描述 把一个字符串中特定的字符全部用给定的字符替换,得到一个新的字符串. 输入 只有一行,由一个字符串和两个字符组成,中间用 ...
- jquery工具方法parseJSON
error : 自定义错误 parseJSON : 字符串转json trim : 去除字符串头尾空字符 parseJSON方法先判断参数是否为字符串,否则返回空对象,再去除字符串头尾空字符,判断是否 ...
- http协议(十)实体首部字段
1.定义 包含在请求和响应中的实体部分所使用的首部,用于补充内容的更新时间等与实体相关的信息 2.Allow 通知客户端能够支持的Request-URI指定资源的所有http方法 如果服务器接收到不支 ...
- matrix-tree
学一发matrix-tree 原来bzoj1016这题是暴搜+玄学并查集过的-数据弱怪我咯 首先matrix-tree需要度数矩阵D,就是说当i=j时D[i][j]为i的度数,否则为0. 还有邻接矩阵 ...
- Linux下误删除后的恢复操作(ext3/ext4)
Linux是作为一个多用户.多任务的操作系统,文件一旦被删除是难以恢复的.尽管删除命令只是在文件节点中作删除标记,并不真正清除文件内容,但是其他用户和一些有写盘动作的进程会很快覆盖这些数据.在日常工程 ...
- django自带wsgi server vs 部署uwsgi+nginx后的性能对比
一.下面先交代一下测试云主机 cpu: root@alexknight:/tmp/webbench-1.5# cat /proc/cpuinfo |grep model model : model n ...
- shipyard安装
1.Start an data volume instance of RethinkDB: # docker run -it -d --name shipyard-rethinkdb-data \ - ...
- 十大经典排序算法总结——JavaScrip版
首先,对于评述算法优劣术语的说明: 稳定:如果a原本在b前面,而a=b,排序之后a仍然在b的前面:即排序后2个相等键值的顺序和排序之前它们的顺序相同 不稳定:如果a原本在b的前面,而a=b,排序之后a ...
- noi题库(noi.openjudge.cn) 1.8编程基础之多维数组T11——T20
T11 图像旋转 描述 输入一个n行m列的黑白图像,将它顺时针旋转90度后输出. 输入 第一行包含两个整数n和m,表示图像包含像素点的行数和列数.1 <= n <= 100,1 <= ...
- HTTP04--CDN知识
一.CDN用途及概念 目的: CDN是内容分布网路(Content Delivery Network)的简称,目的是将网站内容发布到最接近用户的边缘,使用户就近获取内容,提高相应速度. 使用机制: 目 ...