提高你的数据库编程效率: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 ...
随机推荐
- Vijos1019 补丁VS错误[最短路 状态压缩]
描述 错误就是人们所说的Bug.用户在使用软件时总是希望其错误越少越好,最好是没有错误的.但是推出一个没有错误的软件几乎不可能,所以很多软件公司都在疯狂地发放补丁(有时这种补丁甚至是收费的).T公 ...
- memcache的安装和使用
Memcache Memcached是一个高性能的分布式缓存系统.memcached自身不会实现分布式,分布式是由程序来实现的. Memcached一旦安装之后,自身进行管理!预申请一个很大的内存空间 ...
- [No00000C]Word快捷键大全 Word2013/2010/2007/2003常用快捷键大全
Word对于我们办公来说,是不可缺少的办公软件,因为没有它我们可能无法进行许多任务.所以现在的文员和办公室工作的人,最基础的就是会熟悉的使用Office办公软件.在此,为提高大家Word使用水平,特为 ...
- [bzoj3289]Mato的文件管理
Description Mato同学从各路神犇以各种方式(你们懂的)收集了许多资料,这些资料一共有n份,每份有一个大小和一个编号.为了防止他人偷拷,这些资料都是加密过的,只能用Mato自己写的程序才能 ...
- Android测试之Monkey
自己用的测试 C:\Users\Star>adb shell monkey -p com.cmstop.android --monitor-native-crashes -- pct-touch ...
- 使用adb shell卸载程序
个人感觉在命令行中卸载程序要比在手机界面卸载程序要方便许多,配合命令行下的报名查看包名的命令就更加方便了. 1.查看应用准确包名 adb shell pm list package -f |grep ...
- angular留言板
今天使用angularJs写了一个留言板,简单的享受了下angular处理数据的双向绑定的方便:注释已经都写到行间了 <!DOCTYPE html> <html lang=" ...
- fabric批量操作远程操作主机的练习
fabric是python的一个基于命令行的自动化部署框架,用docker开了两个容器来学习fabric. #!/usr/bin/env python #-*- coding=utf-8 -*- fr ...
- C# 发送邮件,QQ企业邮箱测试成功
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.N ...
- VS清除打开项目时的TFS版本控制提示
原文:http://blog.useasp.net/archive/2015/12/15/how-to-permanently-remove-vs-project-TFS-source-version ...