

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 匯出 SQL Server 資料庫物件
<a name="export-sql-server-database-objects"></a>

對於離線來源，您可以上傳描述來源資料庫物件的匯出指令碼檔案。您可以使用任何可用的工具匯出它們。下列索引標籤說明兩種方法：SQL Server Management Studio (SSMS) 和 SQL Server Management Objects (SMO)。

------
#### [ SSMS ]

1. 在 SSMS 的 Object Explorer 中，以滑鼠右鍵按一下要匯出的資料庫。選擇**任務**，然後選擇**產生指令碼**。

1. 選擇**儲存為指令碼檔案**。

1. 在**要產生的檔案**下，選擇**每個物件一個指令碼檔案**，為每個資料庫物件建立個別`.sql`檔案。

1. 在**目錄名稱**中，輸入輸出檔案目錄的路徑。我們建議您建立與資料庫同名的目錄。

1. 針對**另存新檔**，選擇 **Unicode 文字**。

1. 選擇**進階**以開啟**進階指令碼選項**對話方塊。

1. 根據下表設定選項。

1. 選擇**確定**，然後選擇**下一步**以檢閱摘要。

1. 選擇**下一步**以產生指令碼。

1. 選擇**完成**以關閉精靈。

**進階指令碼選項**

在**進階指令碼選項**對話方塊中設定下列選項。


**一般選項**  

| 選項 | Value | 
| --- | --- | 
| ANSI 填補 | False | 
| 附加至 檔案 | False | 
| 檢查物件是否存在 | False | 
| 在錯誤上繼續編寫指令碼 | True | 
| 將 UDDTs轉換為基本類型 | False | 
| 產生相依物件的指令碼 | True | 
| 包含描述性標頭 | False | 
| 包含指令碼參數標頭 | False | 
| 包含系統限制名稱 | False | 
| 結構描述限定物件名稱 | True | 
| 指令碼繫結 | False | 
| 指令碼定序 | True | 
| 指令碼預設值 | True | 
| 指令碼 DROP 和 CREATE | 指令碼 CREATE | 
| 指令碼延伸屬性 | True | 
| 指令碼登入 | False | 
| 指令碼物件層級許可 | False | 
| 指令碼擁有者 | False | 
| 指令碼統計資料 | 請勿編寫統計資料的指令碼 | 
| 指令碼使用資料庫 | True | 
| 要指令碼的資料類型 | 僅限結構描述 | 


**資料表/檢視選項**  

| 選項 | Value | 
| --- | --- | 
| 指令碼變更追蹤 | False | 
| 指令碼檢查限制條件 | True | 
| 指令碼資料壓縮選項 | False | 
| 指令碼外部金鑰 | True | 
| 指令碼全文索引 | True | 
| 指令碼索引 | True | 
| 指令碼主索引鍵 | True | 
| 指令碼觸發條件 | True | 
| 指令碼唯一金鑰 | True | 

------
#### [ SMO ]

SQL Server 管理物件 (SMO) 是用於以程式設計方式管理 SQL Server 的 .NET API。您可以使用 SMO 搭配 PowerShell 或 C\# 來編寫資料庫物件的指令碼，並產生 DDL 檔案以搭配離線來源使用。

**先決條件**
+ Windows PowerShell 5.1 或更新版本，或 PowerShell 7\+
+ `SqlServer` PowerShell 模組 （使用 安裝`Install-Module SqlServer`)
+ .NET Framework 4.6.2 或更新版本，或跨平台的 .NET 6\+

**金鑰指令碼組態**

當您使用 SMO 匯出離線來源的指令碼時，請設定下列指令碼選項：


**必要的 SMO 指令碼選項**  

| 選項 | Value | 
| --- | --- | 
| ToFileOnly | True | 
| Encoding | Unicode | 
| AppendToFile | False | 
| IncludeHeaders | True | 
| IncludeDatabaseContext | True | 
| SchemaQualify | True | 
| AnsiPadding | True | 
| Default | True | 
| DriAll | True | 
| Indexes | True | 
| Triggers | True | 
| FullTextIndexes | True | 
| ExtendedProperties | True | 
| ScriptDataCompression | True | 
| ScriptDrops | False | 
| IncludeIfNotExists | False | 
| WithDependencies | False | 
| NoCollation | True | 
| Permissions | False | 
| ContinueScriptingOnError | True | 

**PowerShell 指令碼範例**

下列指令碼會將所有資料庫物件匯出至個別`.sql`檔案。每個檔案包含單一資料庫物件的一個`CREATE`陳述式。

```
# Export SQL Server database objects using SMO
# Usage: .\Export-Database.ps1 -Database "MyDB" -OutputDir "C:\export\MyDB"

param(
    [string] $ServerInstance = "localhost",         # SQL Server instance name
    [Parameter(Mandatory)] [string] $Database,     # Database to export
    [Parameter(Mandatory)] [string] $OutputDir,    # Output directory for .sql files
    [switch] $TrustServerCertificate               # Skip certificate validation
)

$ErrorActionPreference = "Stop"

# Load the SqlServer module (includes SMO assemblies)
Import-Module SqlServer -ErrorAction Stop

# Connect to SQL Server
$srv = New-Object Microsoft.SqlServer.Management.Smo.Server($ServerInstance)
$srv.ConnectionContext.EncryptConnection = $true
if ($TrustServerCertificate) {
    $srv.ConnectionContext.TrustServerCertificate = $true
}

# Get the database
$db = $srv.Databases[$Database]
if (-not $db) { Write-Error "Database '$Database' not found."; exit 1 }
if (-not (Test-Path $OutputDir)) { New-Item -ItemType Directory -Path $OutputDir -Force | Out-Null }

# Configure scripting options for offline source compatibility
$scripter = New-Object Microsoft.SqlServer.Management.Smo.Scripter($srv)
$opts = $scripter.Options
$opts.ToFileOnly             = $true       # Write directly to files
$opts.Encoding               = [System.Text.Encoding]::Unicode  # Unicode encoding
$opts.AppendToFile           = $false      # One object per file
$opts.IncludeHeaders         = $true       # Add descriptive headers
$opts.IncludeDatabaseContext = $true       # Add USE [database] statement
$opts.SchemaQualify          = $true       # Use schema.object format
$opts.AnsiPadding            = $true       # Include ANSI_PADDING settings
$opts.Default                = $true       # Include default constraints
$opts.DriAll                 = $true       # Include all constraints and keys
$opts.Indexes                = $true       # Include indexes
$opts.Triggers               = $true       # Include triggers
$opts.FullTextIndexes        = $true       # Include full-text indexes
$opts.ExtendedProperties     = $true       # Include extended properties
$opts.ScriptDataCompression  = $true       # Include data compression settings
$opts.ScriptDrops            = $false      # CREATE only, no DROP statements
$opts.IncludeIfNotExists     = $false      # No IF NOT EXISTS wrapper
$opts.WithDependencies       = $false      # Do not script dependent objects
$opts.NoCollation            = $true       # Omit collation clauses
$opts.Permissions            = $false      # Omit permissions
$opts.ContinueScriptingOnError = $true     # Skip errors, continue with next object

# Define which object types to export
$collections = [ordered]@{
    "Schemas"               = "Schema"
    "Tables"                = "Table"
    "Views"                 = "View"
    "StoredProcedures"      = "StoredProcedure"
    "UserDefinedFunctions"  = "UserDefinedFunction"
    "Sequences"             = "Sequence"
    "Synonyms"              = "Synonym"
    "UserDefinedDataTypes"  = "UserDefinedDataType"
    "UserDefinedTableTypes" = "UserDefinedTableType"
    "UserDefinedTypes"      = "UserDefinedType"
    "UserDefinedAggregates" = "UserDefinedAggregate"
    "XmlSchemaCollections"  = "XmlSchemaCollection"
    "Rules"                 = "Rule"
    "Defaults"              = "Default"
    "PartitionSchemes"      = "PartitionScheme"
    "PartitionFunctions"    = "PartitionFunction"
    "Assemblies"            = "SqlAssembly"
    "FullTextCatalogs"      = "FullTextCatalog"
    "FullTextStopLists"     = "FullTextStopList"
    "SearchPropertyLists"   = "SearchPropertyList"
    "SecurityPolicies"      = "SecurityPolicy"
    "ExternalDataSources"   = "ExternalDataSource"
    "ExternalFileFormats"   = "ExternalFileFormat"
}

# System schemas to skip
$sysSchemas = 'dbo','guest','INFORMATION_SCHEMA','sys',
    'db_owner','db_accessadmin','db_securityadmin','db_ddladmin',
    'db_backupoperator','db_datareader','db_datawriter',
    'db_denydatareader','db_denydatawriter'

# Export the CREATE DATABASE statement
$dbScripter = New-Object Microsoft.SqlServer.Management.Smo.Scripter($srv)
$dbScripter.Options.ToFileOnly = $true
$dbScripter.Options.Encoding = [System.Text.Encoding]::Unicode
$dbScripter.Options.IncludeDatabaseContext = $true
$dbScripter.Options.FileName = Join-Path $OutputDir "$Database.Database.sql"
$dbScripter.Script($db)

# Export each object to a separate .sql file
foreach ($colName in $collections.Keys) {
    $col = $db.$colName
    if (-not $col -or $col.Count -eq 0) { continue }

    foreach ($obj in $col) {
        # Skip system objects
        if ($obj.PSObject.Properties['IsSystemObject'] -and $obj.IsSystemObject) { continue }
        if ($colName -eq "Schemas" -and $obj.Name -in $sysSchemas) { continue }

        # Build the output file name: schema.objectname.type.sql
        $schema = if ($obj.PSObject.Properties['Schema']) { $obj.Schema } else { "" }
        $safeName = $obj.Name -replace '[\\/:*?"<>|]', '_'
        $fileName = if ($schema) { "$schema.$safeName.$($collections[$colName]).sql" }
                    else { "$safeName.$($collections[$colName]).sql" }

        $opts.FileName = Join-Path $OutputDir $fileName
        $scripter.Script($obj)
    }
}
```

------