SQL SERVER拓展存储过程
一直都是C#调用数据库的对象,这里介绍的拓展存储过程可以在DB中调用C#的dll并且返回到DB一些信息(表或者字符串)
C#代码如下,主要用以返回一个路径下面的文件,用以测试
下面只是为了创建一个类库,从而产生一个dll,所以操作如下:
using Microsoft.SqlServer.Server; using System; using System.Collections; using System.Collections.Generic; using System.Data.SqlTypes; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; public partial class UserDefinedFunctions { [SqlFunction(FillRowMethodName = "FillRow")] public static IEnumerable DirectoryList(string sRootDir, string sWildCard, bool bIncludeSubDirs) { ArrayList aFileArray = new ArrayList(); DirectorySearch(sRootDir, sWildCard, bIncludeSubDirs, aFileArray); return aFileArray; } private static void DirectorySearch(string directory, string sWildCard, bool bIncludeSubDirs, ArrayList aFileArray) { GetFiles(directory, sWildCard, aFileArray); if (bIncludeSubDirs) { foreach (string d in Directory.GetDirectories(directory)) { DirectorySearch(d, sWildCard, bIncludeSubDirs, aFileArray); } } } private static void GetFiles(string d, string sWildCard, ArrayList aFileArray) { foreach (string f in Directory.GetFiles(d, sWildCard)) { FileInfo fi = new FileInfo(f); object[] column = new object[2]; column[0] = fi.FullName; column[1] = fi.LastWriteTime; aFileArray.Add(column); } } private static void FillRow(object obj, out string filename, out DateTime date) { object[] row = (object[])obj; filename = (string)row[0]; date = (DateTime)row[1]; } }
SQL server 代码
ALTER DATABASE InvestorRelations SET TRUSTWORTHY ON; USE InvestorRelations CREATE ASSEMBLY fExampleTVF FROM 'E:\学习\SessionTest\TestKZCCGC\bin\Debug\TestKZCCGC.dll' WITH PERMISSION_SET=EXTERNAL_ACCESS CREATE FUNCTION fTVFExample( @RootDir nvarchar(max), @WildCard nvarchar(max), @IncludeSubDirs bit ) RETURNS TABLE ( FileName nvarchar(max), LastWriteTime datetime ) AS EXTERNAL NAME fExampleTVF.UserDefinedFunctions.DirectoryList
操作之后你可以查看:
最后可以查询下:
SELECT FILENAME,LASTWRITETIME FROM dbo.fTVFExample('E:\学习','*.ppt',0)
当你查询的时候,有可能会有报错如下:
你可以使用如下代码:
exec sp_configure 'show advanced options', '1'; go reconfigure; go exec sp_configure 'clr enabled', '1' go reconfigure; exec sp_configure 'show advanced options', '1'; go
下面的文章介绍了更多的报错信息,可以参考下,我操作的时候没有遇到
https://www.cnblogs.com/lykbk/p/ewrewrwerwer3454454644.html
当然,这个在某些情况下也是有缺陷的,如果你需要禁用这部分功能,可以参考下面的文章:
https://www.cnblogs.com/chenmh/p/8257369.html