View a markdown version of this page

Export SQL Server database objects - AWS Database Migration Service

Export SQL Server database objects

For an offline source, you upload exported script files that describe your source database objects. You can export them using any available tool. The following tabs describe two approaches: SQL Server Management Studio (SSMS) and SQL Server Management Objects (SMO).

SSMS
  1. In SSMS, in the Object Explorer, right-click the database to export. Choose Tasks, and then choose Generate Scripts.

  2. Choose Save as script file to save the output to .sql files.

  3. Choose the browse button (...) to specify a name and location for the files. We recommend creating a directory with the same name as the database.

  4. For Save as, choose Unicode text.

  5. Choose Advanced to open the Advanced Scripting Options dialog box.

  6. Set the options according to the following tables.

  7. Choose OK, and then choose Next to review the summary.

  8. Choose Next to generate the scripts.

  9. Choose Finish to close the wizard.

Advanced scripting options

Set the following options in the Advanced Scripting Options dialog box.

General options
Option Value
ANSI PaddingFalse
Append to FileFalse
Check for object existenceFalse
Continue scripting on ErrorTrue
Convert UDDTs to Base TypesFalse
Generate Script for Dependent ObjectsTrue
Include Descriptive HeadersFalse
Include Scripting Parameters HeaderFalse
Include system constraint namesFalse
Schema qualify object namesTrue
Script BindingFalse
Script CollationTrue
Script DefaultsTrue
Script DROP AND CREATEScript CREATE
Script Extended PropertiesTrue
Script LoginsFalse
Script Object-Level PermissionsFalse
Script OwnerFalse
Script StatisticsDo not script statistics
Script USE DATABASETrue
Types of data to scriptSchema only
Table/View options
Option Value
Script Change TrackingFalse
Script Check ConstraintsTrue
Script Data Compression OptionsFalse
Script Foreign KeysTrue
Script Full-Text IndexTrue
Script IndexTrue
Script Primary KeysTrue
Script TriggersTrue
Script Unique KeysTrue
SMO

SQL Server Management Objects (SMO) is a .NET API for programmatically managing SQL Server. You can use SMO with PowerShell or C# to script database objects and generate DDL files for use with an offline source.

Prerequisites

  • Windows PowerShell 5.1 or later, or PowerShell 7+

  • The SqlServer PowerShell module (install with Install-Module SqlServer)

  • .NET Framework 4.6.2 or later, or .NET 6+ for cross-platform

Key scripting configuration

When you use SMO to export scripts for an offline source, configure the following scripting options:

Required SMO scripting options
Option Value
ToFileOnlyTrue
EncodingUnicode
AppendToFileFalse
IncludeHeadersTrue
IncludeDatabaseContextTrue
SchemaQualifyTrue
AnsiPaddingTrue
DefaultTrue
DriAllTrue
IndexesTrue
TriggersTrue
FullTextIndexesTrue
ExtendedPropertiesTrue
ScriptDataCompressionTrue
ScriptDropsFalse
IncludeIfNotExistsFalse
WithDependenciesFalse
NoCollationTrue
PermissionsFalse
ContinueScriptingOnErrorTrue

Example PowerShell script

The following script exports all database objects to individual .sql files. Each file contains one CREATE statement for a single database object.

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