

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
<a name="export-sql-server-database-objects"></a>

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.**

1. Pilih **Simpan sebagai file skrip**.

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

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

1. Untuk **Simpan sebagai**, pilih **Teks Unicode**.

1. Pilih **Advanced** untuk membuka kotak dialog **Advanced Scripting Options**.

1. Atur opsi sesuai dengan tabel berikut.

1. Pilih **OK**, lalu pilih **Berikutnya** untuk meninjau ringkasan.

1. Pilih **Berikutnya** untuk menghasilkan skrip.

1. Pilih **Selesai** untuk menutup wizard.

**Opsi skrip lanjutan**

Atur opsi berikut di kotak dialog **Advanced Scripting Options**.


**Opsi umum**  

| Opsi | Nilai | 
| --- | --- | 
| Bantalan ANSI | False | 
| Tambahkan ke File | False | 
| Periksa keberadaan objek | False | 
| Lanjutkan skrip pada Kesalahan | True | 
| Ubah UDDT ke Tipe Dasar | False | 
| Hasilkan Skrip untuk Objek Dependen | True | 
| Sertakan Header Deskriptif | False | 
| Sertakan Header Parameter Scripting | False | 
| Sertakan nama kendala sistem | False | 
| Skema memenuhi syarat nama objek | True | 
| Pengikatan Skrip | False | 
| Skrip Collation | True | 
| Default Skrip | True | 
| Skrip DROP DAN BUAT | Skrip BUAT | 
| Properti Diperpanjang Skrip | True | 
| Log Masuk Skrip | False | 
|  Object-Level Izin Skrip | False | 
| Pemilik Skrip | False | 
| Statistik Skrip | Jangan membuat skrip statistik | 
| Skrip MENGGUNAKAN DATABASE | True | 
| Jenis data ke skrip | Skema saja | 


**Table/View pilihan**  

| Opsi | Nilai | 
| --- | --- | 
| Pelacakan Perubahan Skrip | False | 
| Kendala Pemeriksaan Skrip | True | 
| Opsi Kompresi Data Skrip | False | 
| Script Kunci Asing | True | 
|  Full-Text Indeks Skrip | True | 
| Indeks Skrip | True | 
| Kunci Utama Skrip | True | 
| Pemicu Skrip | True | 
| Kunci Unik Skrip | True | 

------
#### [ 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 dengan`Install-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 | 
| --- | --- | 
| ToFileOnly | True | 
| Encoding | Unicode | 
| AppendToFile | False | 
| IncludeHeaders | Benar | 
| IncludeDatabaseContext | Benar | 
| SchemaQualify | Benar | 
| AnsiPadding | Benar | 
| Default | Benar | 
| DriAll | Benar | 
| Indexes | Benar | 
| Triggers | Benar | 
| FullTextIndexes | Benar | 
| ExtendedProperties | Benar | 
| ScriptDataCompression | Benar | 
| ScriptDrops | Salah | 
| IncludeIfNotExists | Salah | 
| WithDependencies | Salah | 
| NoCollation | Benar | 
| Permissions | Salah | 
| ContinueScriptingOnError | True | 

**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)
    }
}
```

------