sql server 下写net函数,存储过程的方法
新建项目->数据库项目->Microsoft SQLServer ->SQL CLR->SQLServer项目
添加新类sqlclr.cs
public sealed class sqlclr { //正则表达式匹配函数 [SqlFunction(IsDeterministic =true,DataAccess=DataAccessKind.None)] public static SqlBoolean IsMatch(string source,string pattern,int options) { SqlBoolean sqlbool=SqlBoolean.False; if(string.IsNullOrEmpty(source)||string.IsNullOrEmpty(pattern)) { return SqlBoolean.False; } RegexOptions regexOptions=RegexOptions.None; int optionIgnoreCase=1; int optionMultiline=2; if((options & optionIgnoreCase)!=0) { regexOptions=regexOptions |RegexOptions.IgnoreCase; } if((options & optionMultiline)!=0) { regexOptions=regexOptions |RegexOptions.Multiline; } sqlbool=(SqlBoolean)(Regex.IsMatch(source,pattern,regexOptions)); return sqlbool; } //发送邮件函数 [SqlProcedure] [SmtpPermission(SecurityAction.Assert)] [SecurityPermission(SecurityAction.Assert)] public static void SendMail(string to, string from, string subject, string body, string userName, string password, string smtpHost) { MailAddress addressFrom = new MailAddress(from); MailAddress addressTo = new MailAddress(to); MailMessage message = new MailMessage(addressFrom, addressTo); message.Subject = subject;//设置邮件言主题 message.IsBodyHtml = true;//设置邮件正文为html格式 message.Body = body; //设置邮件内容 SmtpClient client = new SmtpClient(smtpHost); //设置发送邮件身份验证方式 //注意如果发件人地址是[email protected],则用户名是abc,而不是[email protected] client.Credentials = new NetworkCredential(userName, password); // client.Send(message); } }
数据库中SQL语句注册dll文件
//----------------------------- use cbjyq_flowdb go sp_configure 'clr enable', 1 GO reconfigure alter database cbjyq_flowdb set trustworthy on; if exists(select * from sys.sysobjects where name='SendMail' and xtype='PC') drop procedure SendMail; if exists(select * from sys.sysobjects where name='IsMatch' and xtype='FS') drop function IsMatch; if exists(select * from sys.assemblies where name='SqlWorkFlow_cw_dll') drop assembly SqlWorkFlow_cw_dll; create assembly SqlWorkFlow_cw_dll from 'E:\项目集合\VSSCodeCenter\xxx系统\TdcbOffice\输出TdcbOffice\SqlWorkFlow_cw.dll' with permission_set=unsafe; go create function dbo.IsMatch ( @source as NVARCHAR(200), @patter as NVARCHAR(200), @option int=3 ) returns bit as EXTERNAL NAME [SqlWorkFlow_cw_dll].[SqlWorkFlow_cw.sqlclr].[IsMatch]; go create procedure dbo.SendMail ( @to as nvarchar(200), @from as nvarchar(200), @subject as nvarchar(200), @body as nvarchar(MAX), @userName as nvarchar(200), @password as nvarchar(200), @smtpHost as nvarchar(200) ) as external name [SqlWorkFlow_cw_dll].[SqlWorkFlow_cw.sqlclr].[SendMail]; go //----------------------------- SQL语句调用测试 select * from ENTITY_MESSAGE where dbo.IsMatch(name,'^[\u4e00-\u9fa5]{3,5}$',3)=1 exec dbo.SendMail @to='[email protected]',@from='[email protected]', @subject='test', @body='This mail was sent by sql procedure', @username='webmaster', @password='123', @smtpHost='smtp.qq.com'