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
-
In SSMS, in the Object Explorer, right-click the database to export. Choose Tasks, and then choose Generate Scripts.
Choose Save as script file to save the output to
.sqlfiles.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.
For Save as, choose Unicode text.
Choose Advanced to open the Advanced Scripting Options dialog box.
Set the options according to the following tables.
Choose OK, and then choose Next to review the summary.
Choose Next to generate the scripts.
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 Padding False Append to File False Check for object existence False Continue scripting on Error True Convert UDDTs to Base Types False Generate Script for Dependent Objects True Include Descriptive Headers False Include Scripting Parameters Header False Include system constraint names False Schema qualify object names True Script Binding False Script Collation True Script Defaults True Script DROP AND CREATE Script CREATE Script Extended Properties True Script Logins False Script Object-Level Permissions False Script Owner False Script Statistics Do not script statistics Script USE DATABASE True Types of data to script Schema only Table/View options Option Value Script Change Tracking False Script Check Constraints True Script Data Compression Options False Script Foreign Keys True Script Full-Text Index True Script Index True Script Primary Keys True Script Triggers True Script Unique Keys True - 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
SqlServerPowerShell module (install withInstall-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
.sqlfiles. Each file contains oneCREATEstatement 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) } }