View a markdown version of this page

Ekspor objek database SQL Server - AWS Database Migration Service

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

Ekspor objek database SQL Server

Untuk sumber offline, Anda mengunggah file skrip yang diekspor yang menjelaskan objek basis data sumber Anda. Anda dapat mengekspornya menggunakan alat apa pun yang tersedia. Tab berikut menjelaskan dua pendekatan: SQL Server Management Studio (SSMS) dan SQL Server Management Objects (SMO).

SSMS
  1. Di SSMS, di Object Explorer, klik kanan database untuk mengekspor. Pilih Tugas, lalu pilih Hasilkan Skrip.

  2. Pilih Simpan sebagai file skrip.

  3. Di bawah File untuk menghasilkan, pilih Satu file skrip per objek untuk membuat .sql file terpisah untuk setiap objek database.

  4. Untuk Nama Direktori, masukkan path ke direktori untuk file output. Sebaiknya buat direktori dengan nama yang sama dengan database.

  5. Untuk Simpan sebagai, pilih Teks Unicode.

  6. Pilih Advanced untuk membuka kotak dialog Advanced Scripting Options.

  7. Atur opsi sesuai dengan tabel berikut.

  8. Pilih OK, lalu pilih Berikutnya untuk meninjau ringkasan.

  9. Pilih Berikutnya untuk menghasilkan skrip.

  10. Pilih Selesai untuk menutup wizard.

Opsi skrip lanjutan

Atur opsi berikut di kotak dialog Advanced Scripting Options.

Opsi umum
Opsi Nilai
Bantalan ANSIFalse
Tambahkan ke FileFalse
Periksa keberadaan objekFalse
Lanjutkan skrip pada KesalahanTrue
Ubah UDDT ke Tipe DasarFalse
Hasilkan Skrip untuk Objek DependenTrue
Sertakan Header DeskriptifFalse
Sertakan Header Parameter ScriptingFalse
Sertakan nama kendala sistemFalse
Skema memenuhi syarat nama objekTrue
Pengikatan SkripFalse
Skrip CollationTrue
Default SkripTrue
Skrip DROP DAN BUATSkrip BUAT
Properti Diperpanjang SkripTrue
Log Masuk SkripFalse
Object-Level Izin SkripFalse
Pemilik SkripFalse
Statistik SkripJangan membuat skrip statistik
Skrip MENGGUNAKAN DATABASETrue
Jenis data ke skripSkema saja
Table/View pilihan
Opsi Nilai
Pelacakan Perubahan SkripFalse
Kendala Pemeriksaan SkripTrue
Opsi Kompresi Data SkripFalse
Script Kunci AsingTrue
Full-Text Indeks SkripTrue
Indeks SkripTrue
Kunci Utama SkripTrue
Pemicu SkripTrue
Kunci Unik SkripTrue
SMO

SQL Server Management Objects (SMO) adalah API .NET untuk mengelola SQL Server secara terprogram. Anda dapat menggunakan SMO dengan PowerShell atau C # untuk skrip objek database dan menghasilkan file DDL untuk digunakan dengan sumber offline.

Prasyarat

  • Windows PowerShell 5.1 atau lebih baru, atau PowerShell 7+

  • SqlServer PowerShell Modul (instal denganInstall-Module SqlServer)

  • .NET Framework 4.6.2 atau yang lebih baru, atau .NET 6+ untuk cross-platform

Konfigurasi skrip kunci

Saat Anda menggunakan SMO untuk mengekspor skrip untuk sumber offline, konfigurasikan opsi skrip berikut:

Opsi skrip SMO yang diperlukan
Opsi Nilai
ToFileOnlyTrue
EncodingUnicode
AppendToFileFalse
IncludeHeadersBenar
IncludeDatabaseContextBenar
SchemaQualifyBenar
AnsiPaddingBenar
DefaultBenar
DriAllBenar
IndexesBenar
TriggersBenar
FullTextIndexesBenar
ExtendedPropertiesBenar
ScriptDataCompressionBenar
ScriptDropsSalah
IncludeIfNotExistsSalah
WithDependenciesSalah
NoCollationBenar
PermissionsSalah
ContinueScriptingOnErrorTrue

Contoh PowerShell skrip

Script berikut mengekspor semua objek database ke .sql file individual. Setiap file berisi satu CREATE pernyataan untuk satu objek database.

# 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) } }