View a markdown version of this page

SQL Server データベースオブジェクトのエクスポート - AWS データベース移行サービス

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

SQL Server データベースオブジェクトのエクスポート

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

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

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

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

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

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

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

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

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

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

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

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

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

汎用オプション
オプション
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
EncodingUnicode
AppendToFile
IncludeHeadersTrue
IncludeDatabaseContextTrue
SchemaQualifyTrue
AnsiPaddingTrue
DefaultTrue
DriAllTrue
IndexesTrue
TriggersTrue
FullTextIndexesTrue
ExtendedPropertiesTrue
ScriptDataCompressionTrue
ScriptDrops
IncludeIfNotExists
WithDependencies
NoCollationTrue
PermissionsFalse
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) } }