什么做书籍的网站,教做面包的网站,青海省制作网站专业,公司网站 开源一、SQLserver启用CLR
查看是否开启CRL#xff0c;如果run_value1#xff0c;则表示开启
EXEC sp_configure clr enabled;
GO
RECONFIGURE;
GO如果未启用#xff0c;则执行如下命令启用CLR
sp_configure clr enabled, 1;
GO
RECONFIGURE;
GO二、创建 CLR 程序集 创建新项…一、SQLserver启用CLR
查看是否开启CRL如果run_value1则表示开启
EXEC sp_configure clr enabled;
GO
RECONFIGURE;
GO如果未启用则执行如下命令启用CLR
sp_configure clr enabled, 1;
GO
RECONFIGURE;
GO二、创建 CLR 程序集 创建新项目 打开 Visual Studio创建一个新的类库项目命名为TcpClientWrapper目标框架选择 .NET Framework 3.5。 编写 TCP 通信代码 在Class1.cs文件中添加如下代码
using System;
using System.Data.SqlTypes;
using System.IO;
using System.Net.Sockets;
using Microsoft.SqlServer.Server;public class TcpClientWrapper
{private static TcpClient client;[SqlFunction]public static SqlString CallTcpService(SqlString host, SqlInt32 port, SqlString message){try{if (client null || !client.Connected){client new TcpClient(host.Value, port.Value);}using (NetworkStream stream client.GetStream()){using (var writer new StreamWriter(stream))using (var reader new StreamReader(stream)){// Send the message to the TCP server.writer.Write(message.Value);writer.Flush();// Read the response from the TCP server.int response reader.Read();char character Convert.ToChar(response);//string response reader.ReadToEnd();return new SqlString(response _ character);}}}catch (Exception ex){return new SqlString(Error: ex.Message);}}
}编译项目 会在 {项目路径}/bin/debug 下生成DLL文件
三、部署程序集到SQLserver
将生成的dll文件上传到SQLserver服务器上记录文件路径执行以下命令将程序集加载到 SQL Server
-- 因为程序中使用了静态成员变量所以需要UNSAFE模式否则会报错建议使用SAFE、EXTERNAL_ACCESS模式
CREATE ASSEMBLY TcpClientWrapper FROM C:\test\TcpClientWrapper.dll WITH PERMISSION_SET UNSAFE;-- 删除 ASSEMBLY
DROP ASSEMBLY TcpClientWrapper;创建函数以调用程序集中的方法
CREATE FUNCTION dbo.CallTcpService(host NVARCHAR(255), port INT, message NVARCHAR(MAX))
RETURNS NVARCHAR(MAX)
AS EXTERNAL NAME TcpClientWrapper.[TcpClientWrapper].CallTcpService;四、调用TCP接口
DECLARE response NVARCHAR(MAX);
SET response dbo.CallTcpService(127.0.0.1, 8899, 好);
PRINT response;数据库端 服务端