2011-10-06 62 views
2

我想用SMO去做幾件在T-SQL中不容易做的事情。但是,我發現的所有示例都是針對C#或Powershell的。有沒有簡單的方法通過T-SQL調用SMO,就像你可以用DMO和sp_OACreate一樣?其中一種方法是通過xp_cmdshell通過PowerShell調用SMO - 但這會很糟糕。建議?通過T-SQL調用SMO?

一個明顯的例子是「通過SMO調用表格」。

謝謝。

+0

你想做什麼事情,具體是?我敢打賭,他們可能在SMO中很容易在T-SQL中完成。 – siride

+0

@siride雖然所有的東西都可以在直接的T-SQL中完成,但使用SMO至少可以讓腳本對象更容易一些。查看[Scripter](https://msdn.microsoft.com/zh-CN/library/microsoft.sqlserver.management.smo.scripter.aspx)和[ScriptingOptions](https://msdn.microsoft.com/zh-cn/ -us /庫/ microsoft.sqlserver.management.smo.scriptingoptions.aspx)。 –

+1

@srutzky:我用過這些,他們(大部分)都很棒。不過,我想知道,如果你應該寫一個C#工具來做到這一點?任何必須通過T-SQL完成的原因? – siride

回答

3

不幸的是,SMO不能通過SQLCLR直接調用。它不僅僅是 - Microsoft.SqlServer.Smo.dll - 不在Supported .NET Framework Libraries列表中,但它被明確禁止。

如果您嘗試通過CREATE ASSEMBLY手動導入DLL,您會收到以下錯誤:

CREATE ASSEMBLY [SMO] 
AUTHORIZATION [dbo] 
FROM 
N'C:\Program Files\Microsoft SQL Server\110\SDK\Assemblies\Microsoft.SqlServer.Smo.dll' 
WITH PERMISSION_SET = UNSAFE; 

返回:

Msg 6596, Level 16, State 1, Line 1
CREATE ASSEMBLY failed because assembly 'Microsoft.SqlServer.Smo' is a system assembly. Consider creating a user assembly to wrap desired functionality.

好了,試試「創建用戶組裝包裝所需的功能」。

如果您的大會上標有PERMISSION_SET = SAFE你:

Msg 6522, Level 16, State 2, Line 1
A .NET Framework error occurred during execution of user-defined routine or aggregate "SmoTest":
System.Security.SecurityException: That assembly does not allow partially trusted callers.

如果您的大會上標有PERMISSION_SET = UNSAFE你:

Msg 6522, Level 16, State 2, Line 1
A .NET Framework error occurred during execution of user-defined routine or aggregate "SmoTest":
System.Exception: This functionality is disabled in the SQLCLR. It is recommended that you execute from your client application.
System.Exception:
at Microsoft.SqlServer.Management.Common.ConnectionManager..ctor()
at Microsoft.SqlServer.Management.Smo.Server..ctor()

UPDATE:

而且,我只是在2007年1月的MSDN論壇上發現了這個相關主題:

'microsoft.sqlserver.batchparser' is malformed or not a pure .NET assembly.

+1

您是否嘗試反編譯程序集,在VS中重新編譯爲一組新的程序集,然後通過SQLCLR運行該程序集?我只是覺得你走得不夠遠。 – siride

+0

@siride好吧,我只是嘗試(一點點),並通過[ILSpy](http://ilspy.net/)獲得源代碼,但沒有時間更新所有的命名空間引用和/或任何其他是必要的。哦,也許如果你有時間嘗試? ;-) –