如何创建 OLE 自动化对象 (Transact-SQL)创建 OLE 自动化对象
调用 sp_OACreate 创建对象。
使用该对象。 调用 sp_OAGetProperty 获取属性值。
调用 sp_OASetProperty 将属性设为新值。
调用 sp_OAMethod 以调用某个方法。
调用 sp_OAGetErrorInfo 获取最新的错误信息。 调用 sp_OADestroy 释放对象。
说明 所有这些步骤都必须在单个 Transact-SQL 语句批处理内执行。在每个语句批处理结束时将自动释放所有创建的 OLE 对象。
using System;
namespace TestSQLCOM{ /// <summary> /// Class1 的摘要说明。 /// </summary> public class TestMath { public TestMath() { } public int AddMe(int a,int b) { return a + b; } }}
/* 首先创建Com 实例 */declare @i intdeclare @ret_code intexec @ret_code = sp_OACreate 'TestSQLCOM.TestMath', @i output
DECLARE @output varchar(255)DECLARE @hr intDECLARE @source varchar(255)DECLARE @description varchar(255)
EXEC @hr = sp_OAGetErrorInfo @i, @source output, @description outputIF @hr = 0BEGIN SELECT @output = ' Source: ' + @source PRINT @output SELECT @output = ' Description: 创建实例失败 ' + @description PRINT @outputENDELSEBEGIN PRINT ' sp_OAGetErrorInfo failed.' RETURNEND-------------------------------------------/* 创建成功,开始调用 */declare @ret intdeclare @intRetCode intEXEC @intRetCode = sp_OAMethod @i,'AddMe',@ret output,100,200
EXEC @hr = sp_OAGetErrorInfo @i, @source output, @description outputIF @hr = 0BEGIN SELECT @output = ' Source: ' + @source PRINT @output SELECT @output = ' Description: 调用方法失败 ' + @description PRINT @outputENDELSEBEGIN PRINT ' sp_OAGetErrorInfo failed.' RETURNEND--------------------------------------------PRINT '返回的结果是' + Str(@ret)
--释放对象exec sp_OADestroy @i
