1. 程式人生 > >sql server中調用c#寫的dll裏的方法

sql server中調用c#寫的dll裏的方法

lib null all varchar 什麽什麽 server 調用dll func 雲服務

最近有一項目:

一超市管理系統單機版,運行在WIN2003+SQL2005上,每天超市關門都都會關電腦,現客戶要新加功能,每天關門下班後回家可以上網查看超市管理系統的數據庫裏的相關數據,然後再做一些原系統沒有的統計分析等,老系統不能做大改動,像升級到WIN2012+SQL2012等這些操作,改動越小越好。

現在的想法是:阿裏雲買臺服務器,裝上SQL,然後建立的數據庫和超市管理系統上的數據庫一毛一樣,然後想辦法,當超市管理系統數據庫裏的增表增刪改的時候,同步阿裏雲服務器上的數據庫保持數據一致,

然後剩下的就是做自己的網站連接阿裏雲上的數據庫做統計分析就好了

上網到處問網友,以前的技術經理給了如下方案:



using System.Text.RegularExpressions;

namespace MSSQLExtMethod
{
public class RegexExtends
{
[Microsoft.SqlServer.Server.SqlFunction]
public static bool IsMath(string input, string patten)
{
return !string.IsNullOrEmpty(input) && new Regex(patten).IsMatch(input);

}
[Microsoft.SqlServer.Server.SqlFunction]
public static string Math(string input, string patten)
{
return string.IsNullOrEmpty(input) ? "" : new Regex(patten).Match(input).Value;
}
[Microsoft.SqlServer.Server.SqlFunction]
public static string Replace(string input, string patten, string replace)
{
return string.IsNullOrEmpty(input) ? "" : new Regex(patten).Replace(input, replace);
}
}
}

-------------------------------------------------

create assembly Regex from ‘E:\Test\Libs\MSSQLExtMethod.Regex\MSSQLExtMethod.Regex\bin\Debug\MSSQLExtMethod.Regex.dll‘ with permission_set = SAFE

exec sp_configure ‘clr enabled‘,1
RECONFIGURE

create function [dbo].[Regex.Math](@Input nvarchar(max),@Regex nvarchar(max))
returns nvarchar(max) with execute as caller
as
external NAME [Regex].[MSSQLExtMethod.RegexExtends].[Math]
go

create function [dbo].[Regex.Replace](@Input nvarchar(max),@Regex nvarchar(max),@Replace nvarchar(max))
returns nvarchar(max) with execute as caller
as
external NAME [Regex].[MSSQLExtMethod.RegexExtends].[Replace]
go

create function [dbo].[Regex.IsMath](@Input nvarchar(max),@Regex nvarchar(max))
returns bit with execute as caller
as
external NAME [Regex].[MSSQLExtMethod.RegexExtends].[IsMath]
go

------------------------------------------------------------------

declare
@regex nvarchar(500)
,@replace nvarchar(500)
,@input nvarchar(500)
,@regex2 nvarchar(500)
,@input2 nvarchar(500)


select @regex = ‘^(1[3456789][0-9])[0-9]{4}([0-9]{4})$‘
,@input = ‘13912345678‘
,@replace = ‘$1****$2‘

select @regex2=‘1[3456789][0-9]{6}‘
,@input2=‘13100000000,13922222222‘

select dbo.[Regex.Replace](@input,@regex,@replace)
select dbo.[Regex.Math](@input2,@regex2)
select dbo.[Regex.IsMath](@input2,@regex2)




第一塊代碼,.net 類庫,第二塊代碼類庫註冊到 MSSQL 中形成函數,第三塊代碼調用實例

今天自己測試了一下,發現只有.NET 2.0的DLL才可以,開始我是.NET 4.0的,總是報那個什麽什麽權限錯誤之類的。。


這樣只要在SQL2005的表中加個觸發器,有數據變動的時候就調用DLL裏的方法訪問遠程接口進行增刪改遠程數據庫就好了


另SQL非免費版裏好像有個‘鏡像’功能,和一個‘復制’功能,不知道能不能用,沒有學過的。。。


自己在VS2W017中做的.NET 2.0的DLL示例方法的源碼:

http://ohpxbzczu.bkt.clouddn.com/SQL2005ExecDLLDemo.zip

sql server中調用c#寫的dll裏的方法