SqlServerManagementObjects簡介

字號:

Smo是SqlServer Management Objects的簡稱,由SQL2005提供的管理對象,sql-dmo的邏輯進化版本,主要功能由C:Program FilesMicrosoft SQL Server90SDKAssemblies下面的Microsoft.SqlServer.Smo.dll文件中的相關(guān) 對象來實現(xiàn),可以直接由vs2005開發(fā)的程序來引用。
    msdn參考文檔:
    http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.aspx。
    文檔中他列舉了7條大的功能,其實毫不夸張地說,只要SQL Server Management Studio能實現(xiàn)的東西,用smo都能實現(xiàn),因為SQL Server Management Studio就是用smo開發(fā)的。如果你有足夠的實力,完全可以開發(fā)一個可以藐視SQL Server Management Studio的工具,比如加入智能感知的功能。
    具體詳細應(yīng)用這里就不展開了,對象太多...只舉一個例子,很多人問的如何生成sql對象的腳本:
    --先搞一個測試環(huán)境
    use tempdb
    create table test(id int identity(1,1))
    //添加引用
    //Microsoft.SqlServer.ConnectionInfo.dll
    //Microsoft.SqlServer.Smo.dll
    Microsoft.SqlServer.Management.Common.ServerConnection conn = new Microsoft.SqlServer.Management.Common.ServerConnection(
    new System.Data.SqlClient.SqlConnection("server=localhost;uid=sa;pwd=***;database=master"));//一個數(shù)據(jù)庫連接字符串
    Microsoft.SqlServer.Management.Smo.Server server = new Microsoft.SqlServer.Management.Smo.Server(conn);
    Microsoft.SqlServer.Management.Smo.Database db = server.Databases["tempdb"];
    Microsoft.SqlServer.Management.Smo.Table tb= db.Tables["test"];
    System.Collections.Specialized.StringCollection sc= tb.Script();
    foreach (String s in sc)
    {
    Console.WriteLine(s);
    }
    輸出: SET ANSI_NULLS ON SET QUOTED_IDENTIFIER ON CREATE TABLE [dbo].[test]( [id] [int] IDENTITY(1,1) NOT NULL ) ON [PRIMARY]