SMO (SQL Server Management Objects) 是 SQL Server 2005 引入的 .NET 管理物件模型,取代舊版 SQL-DMO。SMO 封裝在 Microsoft.SqlServer.Smo.dll,提供豐富的物件階層 (Server, Database, Table, Index, StoredProcedure...),**凡 SSMS (SQL Server Management Studio) 能做的事,SMO 幾乎都能用程式碼自動化**。本文介紹 SMO 核心組件、參考文件、經典用例:產生資料庫物件建立腳本。
C:\Program Files\Microsoft SQL Server\<版本>\SDK\Assemblies\Microsoft.SqlServer.ConnectionInfo.dllMicrosoft.SqlServer.Smo.dllMicrosoft.SqlServer.Management.Sdk.Sfc.dll (間接相依)Microsoft.SqlServer.SqlManagementObjects (跨平台、無需安裝 SQL Server)。
Server
└─ Databases[Database]
├─ Tables[Table] → Columns[Column], Indexes[Index], ForeignKeys[ForeignKey], Triggers[Trigger]...
├─ Views[View]
├─ StoredProcedures[StoredProcedure]
├─ UserDefinedFunctions[UserDefinedFunction]
├─ Users[User], Roles[Role], Schemas[Schema]
└─ ...
每個物件均提供 Script() 方法產生 T-SQL 建立腳本,Refresh() 同步最新中繼資料,Alter() 套用屬性變更。
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using System;
using System.Collections.Specialized;
public class SMODemo
{
public static void GenerateTableScript()
{
// 1. 建立連線 (支援 Windows/ SQL 驗證)
var conn = new ServerConnection("localhost", "sa", "YourPassword");
// 或使用連線字串:new ServerConnection(new SqlConnection("Server=.;Database=master;Uid=sa;Pwd=...;"));
// 2. 連接 Server 物件
var server = new Server(conn);
// 3. 取得目標資料庫與資料表
var db = server.Databases["tempdb"];
var table = db.Tables["test", "dbo"]; // 名稱, Schema
if (table == null)
{
Console.WriteLine("Table not found.");
return;
}
// 4. 產生腳本選項 (可選)
var scripter = new Scripter(server);
scripter.Options.ScriptDrops = false;
scripter.Options.WithDependencies = true; // 包含相依物件 (索引、FK、預設值...)
scripter.Options.Indexes = true;
scripter.Options.DriAll = true; // 所有宣告式參考完整性
scripter.Options.ClusteredIndexes = true;
scripter.Options.NonClusteredIndexes = true;
// 5. 產生並輸出腳本
StringCollection scripts = table.Script(scripter.Options);
foreach (string s in scripts)
{
Console.WriteLine(s);
Console.WriteLine("GO");
}
}
}
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [dbo].[test](
[id] [int] IDENTITY(1,1) NOT NULL
) ON [PRIMARY]
GO
| 場景 | SMO 關鍵物件/方法 |
|---|---|
| 自動化部署 / CI/CD | Transfer 類別 (資料/結構遷移), Backup/Restore 物件 |
| 結構比對與同步 | Database.Compare (需額外邏輯), 第三方 SqlSchemaCompare (基於 SMO) |
| 效能監控與診斷 | Server.EnumProcesses, Database.EnumTransactions, 存取 DMV 封裝 |
| 安全性管理 | Login, User, Role, Grant/Deny/Revoke 方法 |
| 開發自訂管理工具 | 整合 IntelliSense (需搭配 Microsoft.SqlServer.Management.UI.VSIntegration) |
Server.SetDefaultInitFields 預載必要屬性,避免 N+1 往返。SmoException / ConnectionFailureException。Task.Run 或 BackgroundWorker 執行。SMO 是 .NET 開發者打造 SQL Server 自動化管理工具、部署管線、客製化監控儀表板的利器。掌握其物件模型與 Script() 機制,即可將手動 SSMS 操作轉化為可版控、可重複、可審計的程式碼。