自定义函数和存储过程在.net里其实都是方法。只是方法上方标注[Microsoft.SqlServer.Server.SqlProcedure]
和[Microsoft.SqlServer.Server.SqlFunction]不同而已。自定义函数又分TVF函数和Scalar两种,最大区别在于TVF返回表后者返回Scalar(标量),这一篇我们做一下比较。
先看两段代码
存储过程:
SQLCLR(二)存储过程和自定义函数using System;
SQLCLR(二)存储过程和自定义函数
using System.Data;
SQLCLR(二)存储过程和自定义函数
using System.Data.SqlClient;
SQLCLR(二)存储过程和自定义函数
using System.Data.SqlTypes;
SQLCLR(二)存储过程和自定义函数
using Microsoft.SqlServer.Server;
SQLCLR(二)存储过程和自定义函数
SQLCLR(二)存储过程和自定义函数
SQLCLR(二)存储过程和自定义函数
public partial class StoredProcedures
执行存储过程
SQLCLR(二)存储过程和自定义函数DECLARE @name nvarchar(4000)
SQLCLR(二)存储过程和自定义函数
DECLARE @outstr nvarchar(4000)
SQLCLR(二)存储过程和自定义函数
set @name='david fan'
SQLCLR(二)存储过程和自定义函数
-- TODO: 在此处设置参数值。
SQLCLR(二)存储过程和自定义函数
EXECUTE [TestProject].[dbo].[TestStoredProcedure] 
SQLCLR(二)存储过程和自定义函数   
@name
SQLCLR(二)存储过程和自定义函数  ,
@outstr OUTPUT
SQLCLR(二)存储过程和自定义函数
print @outstr

结果如下
SQLCLR(二)存储过程和自定义函数
输出参数返回值
SQLCLR(二)存储过程和自定义函数 
自定义函数
一,TVF函数
示例函数的作用是搜索目录下的某一类型的文件
SQLCLR(二)存储过程和自定义函数using System;
SQLCLR(二)存储过程和自定义函数
using System.Data;
SQLCLR(二)存储过程和自定义函数
using System.Data.Sql;
SQLCLR(二)存储过程和自定义函数
using System.Data.SqlTypes;
SQLCLR(二)存储过程和自定义函数
using Microsoft.SqlServer.Server;
SQLCLR(二)存储过程和自定义函数
using System.Collections;
SQLCLR(二)存储过程和自定义函数
using System.IO;
SQLCLR(二)存储过程和自定义函数
using System.Security.Principal;
SQLCLR(二)存储过程和自定义函数
SQLCLR(二)存储过程和自定义函数
public partial class UserDefinedFunctions
}
因为这个函数对于sqlserver来讲要访问外部资源,所以需要配置一下项目和sqlserver2005
项目右键属性数据库,权限级别外部
SQLCLR(二)存储过程和自定义函数
打开sqlserver2005查询分析器执行下边语句 TestProject 为我的数据库名,你的如果不是,当然需要修改了。
SQLCLR(二)存储过程和自定义函数ALTER DATABASE TestProject SET TRUSTWORTHY ON;
成功后,项目右键部署

查询分析器中执行
SQLCLR(二)存储过程和自定义函数SELECT * FROM [TestProject].[dbo].[FileListCs] (
SQLCLR(二)存储过程和自定义函数   
'c:\'
SQLCLR(二)存储过程和自定义函数  ,
'*.txt')
结果如下
SQLCLR(二)存储过程和自定义函数
二,Scalar 函数
这类函数返回类型如图,像SqlString这类sqlserver的scalar类型
SQLCLR(二)存储过程和自定义函数
下面就是这类函数的一个小例子。
SQLCLR(二)存储过程和自定义函数using System;
SQLCLR(二)存储过程和自定义函数
using System.Data;
SQLCLR(二)存储过程和自定义函数
using System.Data.SqlClient;
SQLCLR(二)存储过程和自定义函数
using System.Data.SqlTypes;
SQLCLR(二)存储过程和自定义函数
using Microsoft.SqlServer.Server;
SQLCLR(二)存储过程和自定义函数
SQLCLR(二)存储过程和自定义函数
public partial class UserDefinedFunctions
;
sqlserver查询查询分析器中运行如下语句
SQLCLR(二)存储过程和自定义函数SELECT [TestProject].[dbo].[ScalarFunction] ()
结果如下
SQLCLR(二)存储过程和自定义函数
第二篇完成,谢谢大家指教!

相关文章: