- 新建一个类库程Class Library(即可),项目名称为ZCJ.SQL
- 将项目中的类Class1命名为SendPhoneMsg,在这个类中写入如下代码
- 这里写的是一个数据调用程序发送短消息的代码,方法具体处理什么业务可以自己修改
-
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.SqlServer.Server; using System.Data.SqlTypes; using System.Text.RegularExpressions; using System.Net; using System.IO; namespace ZCJ { public partial class SendPhoneMsg { /// <summary> /// 数据库调用发送手机消息 /// </summary> /// <param name="Msg">长度195</param> /// <param name="Tel">手机号</param> /// <returns></returns> [SqlFunction(IsDeterministic = true, DataAccess = DataAccessKind.None)] public static SqlString SendMsg(SqlString Msg, SqlString Tel) { try { string message = Msg.Value, username = "接口名", password = "接口密码", url = "接口地址"; byte[] byteArray = Encoding.UTF8.GetBytes("mobile=" + Tel.Value + "&message=" + message); HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url)); string auth = "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(username + ":" + password)); webRequest.Headers.Add("Authorization", auth); webRequest.Method = "POST"; webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.ContentLength = byteArray.Length; Stream newStream = webRequest.GetRequestStream(); newStream.Write(byteArray, 0, byteArray.Length); newStream.Close(); HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse(); StreamReader php = new StreamReader(response.GetResponseStream(), Encoding.Default); string Message = php.ReadToEnd();//{"error":0,"msg":"ok"} var result = "1:发送成功"; if (Message.IndexOf("ok") > 0) result = "1:发送成功"; else result = "0:发送失败"; return (SqlString)result; } catch (Exception ex) { return (SqlString)"0:发送失败" + ex.Message; } } } }
-
下面打开SQL Server 2008的管理界面,我们需要把这个dll部署到数据库中,
然后再注册一个方法,但是在这之前需要在SQL Server中开启CLR调用功能,
运行下面的SQL 语句exec sp_configure 'clr enabled', 1; reconfigure;
- 获得当前数据公共权限 trustworthy
alter database 数据库名 set trustworthy on;
- 运行下面的语句从这个dll中抽取中间语言(IL),如果你自己试验,注意修改dll文件存放路径
create assembly ZCJ from'F:projectzhongchoujiaCodesCJCJ.SQLinDebugCJ.dll' WITH PERMISSION_SET = EXTERNAL_ACCESS;
上面这句话执行完后会在sql中会出现
- 再写一个SQL函数来注册这个Assembly,代码如下
create function dbo.SendMsg(@Msg as nvarchar(195),@Tel as nvarchar(11)) returns nvarchar(max) with returns null on null input external name [ZCJ].[ZCJ.SendPhoneMsg].[SendMsg] go
注意 external name [zcj].[zcj.sendPhoneMsg].[SendMsg]
external name [assembly(也就是上面创建的assemblyName不是程序集名)].[assemblyName.ClassName].[MethodName]
- 测试调用方法