本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
导出 SQL 服务器数据库对象
对于离线源,您可以上传描述源数据库对象的导出脚本文件。您可以使用任何可用的工具将其导出。以下选项卡描述了两种方法:SQL Server Management Studio (SSMS) 和 SQL Server 管理对象 (SMO)。
- SSMS
-
在 SSMS 的对象资源管理器中,右键单击要导出的数据库。选择 “任务”,然后选择 “生成脚本”。
选择 “另存为脚本文件”。
在 “要生成的文件” 下,选择 “每个对象一个脚本
.sql文件”,为每个数据库对象创建一个单独的文件。在目录名中,输入输出文件的目录路径。我们建议创建一个与数据库同名的目录。
对于另存为,请选择 Unicode 文本。
选择 “高级” 打开 “高级脚本选项” 对话框。
根据下表设置选项。
选择 “确定”,然后选择 “下一步” 以查看摘要。
选择 “下一步” 生成脚本。
选择 “完成” 关闭向导。
高级脚本选项
在 “高级脚本选项” 对话框中设置以下选项。
常规选项 Option 值 ANSI 填充物 False 追加到文件 False 检查对象是否存在 False 出错时继续编写脚本 True 将 UDDT 转换为基本类型 False 为依赖对象生成脚本 True 包括描述性标题 False 包括脚本参数标题 False 包括系统约束名称 False 架构限定对象名称 True 脚本绑定 False 脚本排序规则 True 脚本默认值 True 脚本删除并创建 脚本创建 脚本扩展属性 True 脚本登录 False 脚本 Object-Level 权限 False 脚本所有者 False 脚本统计信息 不要使用脚本统计信息 脚本使用数据库 True 要编写脚本的数据类型 仅限架构 Table/View 选项 Option 值 脚本变更跟踪 False 脚本检查约束 True 脚本数据压缩选项 False 脚本外键 True 脚本 Full-Text 索引 True 脚本索引 True 脚本主键 True 脚本触发器 True 脚本唯一密钥 True - SMO
-
SQL 服务器管理对象 (SMO) 是一个.NET API,用于以编程方式管理 SQL Server。您可以使用 SMO 和 C# 来编写数据库对象脚本并生成 DDL 文件以供离线源使用。 PowerShell
先决条件
Windows PowerShell 5.1 或更高版本,或 PowerShell 7+
SqlServerPowerShell 模块(使用安装Install-Module SqlServer).NET Framework 4.6.2 或更高版本,或者跨平台的.NET 6+
按键脚本配置
使用 SMO 导出离线源的脚本时,请配置以下脚本选项:
必需的 SMO 脚本选项 Option 值 ToFileOnlyTrue EncodingUnicode AppendToFileFalse IncludeHeadersTrue IncludeDatabaseContextTrue SchemaQualifyTrue AnsiPaddingTrue DefaultTrue DriAllTrue IndexesTrue TriggersTrue FullTextIndexesTrue ExtendedPropertiesTrue ScriptDataCompressionTrue ScriptDropsFalse IncludeIfNotExistsFalse WithDependenciesFalse NoCollationTrue PermissionsFalse ContinueScriptingOnErrorTrue PowerShell 脚本示例
以下脚本将所有数据库对象导出到单个
.sql文件。每个文件都包含针对单个数据库对象的一条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) } }