如何建立 OLE Automation 物件 (Transact-SQL)
建立 OLE Automation 物件
調用 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 int
declare @ret_code int
exec @ret_code = sp_OACreate 'TestSQLCOM.TestMath', @i output
DECLARE @output varchar(255)
DECLARE @hr int
DECLARE @source varchar(255)
DECLARE @description varchar(255)
EXEC @hr = sp_OAGetErrorInfo @i, @source output, @description output
IF @hr = 0
BEGIN
SELECT @output = ' Source: ' + @source
PRINT @output
SELECT @output = ' Description: 建立執行個體失敗 ' + @description
PRINT @output
END
ELSE
BEGIN
PRINT ' sp_OAGetErrorInfo failed.'
RETURN
END
-------------------------------------------
/* 建立成功,開始調用 */
declare @ret int
declare @intRetCode int
EXEC @intRetCode = sp_OAMethod @i,'AddMe',@ret output,100,200
EXEC @hr = sp_OAGetErrorInfo @i, @source output, @description output
IF @hr = 0
BEGIN
SELECT @output = ' Source: ' + @source
PRINT @output
SELECT @output = ' Description: 調用方法失敗 ' + @description
PRINT @output
END
ELSE
BEGIN
PRINT ' sp_OAGetErrorInfo failed.'
RETURN
END
--------------------------------------------
PRINT '返回的結果是' + Str(@ret)
--釋放對象
exec sp_OADestroy @i