

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# SQL Server データベースオブジェクトのエクスポート
<a name="export-sql-server-database-objects"></a>

オフラインソースの場合は、ソースデータベースオブジェクトを記述するエクスポートされたスクリプトファイルをアップロードします。使用可能な任意のツールを使用してエクスポートできます。次のタブでは、SQL Server Management Studio (SSMS) と SQL Server Management Objects (SMO) の 2 つのアプローチについて説明します。

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

1. SSMS の Object Explorer で、エクスポートするデータベースを右クリックします。**タスク**を選択し、**スクリプトの生成**を選択します。

1. **スクリプトファイルとして保存** を選択します。

1. **生成するファイル**で、**オブジェクトごとに 1 つのスクリプトファイル**を選択して、データベースオブジェクトごとに個別の`.sql`ファイルを作成します。

1. **ディレクトリ名**に、出力ファイルのディレクトリへのパスを入力します。データベースと同じ名前のディレクトリを作成することをお勧めします。

1. **名前を付けて保存** で、**Unicode テキスト**を選択します。

1. **Advanced** を選択して、**Advanced Scripting Options** ダイアログボックスを開きます。

1. 次の表に従ってオプションを設定します。

1. **OK** を選択し、次**へ** を選択して概要を確認します。

1. **Next** を選択してスクリプトを生成します。

1. **完了** を選択してウィザードを閉じます。

**高度なスクリプトオプション**

**高度なスクリプトオプション**ダイアログボックスで次のオプションを設定します。


**汎用オプション**  

| オプション | 値 | 
| --- | --- | 
| ANSI パディング | 誤 | 
| ファイルに追加する | 誤 | 
| オブジェクトの存在を確認する | 誤 | 
| エラー時のスクリプティングを続行する | 正 | 
| UDDTsをベースタイプに変換する | 誤 | 
| 依存オブジェクトのスクリプトを生成する | 正 | 
| 説明ヘッダーを含める | 誤 | 
| スクリプトパラメータヘッダーを含める | 誤 | 
| システム制約名を含める | 誤 | 
| スキーマ修飾オブジェクト名 | 正 | 
| スクリプトバインディング | 誤 | 
| スクリプト照合 | 正 | 
| スクリプトのデフォルト | 正 | 
| スクリプトの削除と作成 | スクリプトの作成 | 
| スクリプト拡張プロパティ | 正 | 
| スクリプトログイン | 誤 | 
| オブジェクトレベルのアクセス許可のスクリプト | 誤 | 
| スクリプト所有者 | 誤 | 
| スクリプト統計 | 統計をスクリプト化しない | 
| スクリプト使用データベース | 正 | 
| スクリプト化するデータのタイプ | スキーマのみ | 


**テーブル/表示オプション**  

| オプション | 値 | 
| --- | --- | 
| スクリプト変更の追跡 | 誤 | 
| スクリプトチェックの制限 | 正 | 
| スクリプトデータ圧縮オプション | 誤 | 
| スクリプト外部キー | 正 | 
| スクリプトフルテキストインデックス | 正 | 
| スクリプトインデックス | 正 | 
| スクリプトのプライマリキー | 正 | 
| スクリプトトリガー | 正 | 
| スクリプトの一意のキー | 正 | 

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

SQL Server Management Objects (SMO) は、SQL Server をプログラムで管理するための .NET API です。PowerShell または C\# で SMO を使用してデータベースオブジェクトをスクリプト化し、オフラインソースで使用する DDL ファイルを生成できます。

**前提条件**
+ Windows PowerShell 5.1 以降、または PowerShell 7 以降
+ `SqlServer` PowerShell モジュール ( でインストール`Install-Module SqlServer`)
+ .NET Framework 4.6.2 以降、またはクロスプラットフォーム用の .NET 6\+

**キースクリプト設定**

SMO を使用してオフラインソースのスクリプトをエクスポートする場合は、次のスクリプトオプションを設定します。


**必要な SMO スクリプトオプション**  

| オプション | 値 | 
| --- | --- | 
| ToFileOnly | 正 | 
| Encoding | Unicode | 
| AppendToFile | 誤 | 
| IncludeHeaders | True | 
| IncludeDatabaseContext | True | 
| SchemaQualify | True | 
| AnsiPadding | True | 
| Default | True | 
| DriAll | True | 
| Indexes | True | 
| Triggers | True | 
| FullTextIndexes | True | 
| ExtendedProperties | True | 
| ScriptDataCompression | True | 
| ScriptDrops | 誤 | 
| IncludeIfNotExists | 誤 | 
| WithDependencies | 誤 | 
| NoCollation | True | 
| Permissions | False | 
| ContinueScriptingOnError | 正 | 

**PowerShell スクリプトの例**

次のスクリプトは、すべてのデータベースオブジェクトを個々の`.sql`ファイルにエクスポートします。各ファイルには、1 つのデータベースオブジェクトに対して 1 つの`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)
    }
}
```

------