SqlServerManagementObjects簡(jiǎn)介

字號(hào):

Smo是SqlServer Management Objects的簡(jiǎn)稱,由SQL2005提供的管理對(duì)象,sql-dmo的邏輯進(jìn)化版本,主要功能由C:Program FilesMicrosoft SQL Server90SDKAssemblies下面的Microsoft.SqlServer.Smo.dll文件中的相關(guān) 對(duì)象來(lái)實(shí)現(xiàn),可以直接由vs2005開(kāi)發(fā)的程序來(lái)引用。
    msdn參考文檔:
    http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.aspx。
    文檔中他列舉了7條大的功能,其實(shí)毫不夸張地說(shuō),只要SQL Server Management Studio能實(shí)現(xiàn)的東西,用smo都能實(shí)現(xiàn),因?yàn)镾QL Server Management Studio就是用smo開(kāi)發(fā)的。如果你有足夠的實(shí)力,完全可以開(kāi)發(fā)一個(gè)可以藐視SQL Server Management Studio的工具,比如加入智能感知的功能。
    具體詳細(xì)應(yīng)用這里就不展開(kāi)了,對(duì)象太多...只舉一個(gè)例子,很多人問(wèn)的如何生成sql對(duì)象的腳本:
    --先搞一個(gè)測(cè)試環(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"));//一個(gè)數(shù)據(jù)庫(kù)連接字符串
    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]