sqlpackage-import-export
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseMove a whole database with SqlPackage: dacpac and bacpac
使用 SqlPackage 迁移整个数据库:dacpac 和 bacpac
This owns the four-action decision for moving an entire existing database as a portable file, and
the command line for each action. Building a dacpac from a source-controlled SQL project, shipping
it through CI, its refactorlog and its pre and post deployment scripts are .
Azure SQL Database's own automated backups and point-in-time or geo-restore are
. Loading rows into a table that already exists is .
Vector indexes themselves are .
sql-database-projectsrestore-and-recoverbulk-load-and-bulk-copyvector-search-azure-sql本文负责决定如何将整个现有数据库作为可移植文件迁移的四种操作,并给出每种操作对应的命令行。从源代码管理的 SQL 项目构建 dacpac、通过 CI 交付该文件,以及处理它的 refactorlog 和部署前后脚本,均属于 。Azure SQL Database 自带的自动备份以及时间点还原或异地还原,属于 。向已经存在的表中加载数据行属于 。向量索引本身属于 。
sql-database-projectsrestore-and-recoverbulk-load-and-bulk-copyvector-search-azure-sqlScope
范围
- Includes moving the database itself from the local Azure SQL Database container up to Azure SQL Database.
- Pointing the application's connection string at the cloud database, and first-time setup of the local container, are separate workflows.
- 包括将数据库本身从本地 Azure SQL Database 容器迁移到 Azure SQL Database。
- 将应用程序连接字符串指向云端数据库,以及首次设置本地容器,都是独立的工作流。
Read the property list for the action before you write the command
编写命令前,先阅读相应操作的属性列表
Properties are per action. is an Extract property and is not accepted by
Export. There is no catalog of properties that spans the actions, so ask the build in front of you:
ExtractAllTableDatabash
sqlpackage /version:True
sqlpackage /Action:Export /?An unknown property is refused before any connection is attempted:
text
$ sqlpackage /Action:Export /p:ExportAllTableData=true /TargetFile:app.bacpac /SourceServerName:your-server.database.windows.net /SourceDatabaseName:app
*** 'ExportAllTableData' is not a valid argument for the 'Export' action.A property can also be real, documented and still unavailable: is the .NET
Framework build's default, and Learn records as the only option on the cross-platform
build.
/p:Storage=FileMemoryEvery parameter in this skill is written in long form. The same help output gives each one a short
form, as , as , as , and the two forms are
interchangeable.
/Action/a/SourceFile/sf/TargetFile/tf属性因操作而异。 是 Extract 属性,Export 不接受。不存在一份覆盖所有操作的属性目录,因此应查询当前使用的版本:
ExtractAllTableDatabash
sqlpackage /version:True
sqlpackage /Action:Export /?程序会在尝试建立任何连接之前拒绝未知属性:
text
$ sqlpackage /Action:Export /p:ExportAllTableData=true /TargetFile:app.bacpac /SourceServerName:your-server.database.windows.net /SourceDatabaseName:app
*** 'ExportAllTableData' is not a valid argument for the 'Export' action.某个属性也可能确实存在且有文档记录,却仍然无法使用: 是 .NET Framework 版本的默认值,而 Microsoft Learn 将 记录为跨平台版本的唯一选项。
/p:Storage=FileMemory本 skill 中的每个参数均采用完整形式。同一份帮助输出还会给出每个参数的短形式,例如 对应 、 对应 、 对应 ,两种形式可以互换使用。
/Action/a/SourceFile/sf/TargetFile/tfThe four actions, as four commands
四种操作及对应命令
| Action | Direction | Default contents | File |
|---|---|---|---|
| Extract | database to file | schema only | writes |
| Publish | file to database | schema only | reads |
| Export | database to file | schema and every base table's rows | writes |
| Import | file to database | schema and every base table's rows | reads |
Extract:
bash
sqlpackage /Action:Extract /TargetFile:app.dacpac /DiagnosticsFile:extract.log \
/SourceServerName:your-server.database.windows.net /SourceDatabaseName:<database> \
/SourceUser:<user> /SourcePassword:"$SQLPACKAGE_PASSWORD" \
/p:ExtractAllTableData=false /p:VerifyExtraction=trueExport:
bash
sqlpackage /Action:Export /TargetFile:app.bacpac /DiagnosticsFile:export.log \
/SourceServerName:your-server.database.windows.net /SourceDatabaseName:<database> \
/SourceUser:<user> /SourcePassword:"$SQLPACKAGE_PASSWORD" \
/p:VerifyExtraction=true /p:LongRunningCommandTimeout=0Import:
bash
sqlpackage /Action:Import /SourceFile:app.bacpac /DiagnosticsFile:import.log \
/TargetServerName:your-server.database.windows.net /TargetDatabaseName:<new-database> \
/TargetUser:<user> /TargetPassword:"$SQLPACKAGE_PASSWORD" \
/p:DatabaseEdition=Standard /p:DatabaseServiceObjective=S1Publish:
bash
sqlpackage /Action:Publish /SourceFile:app.dacpac \
/TargetServerName:your-server.database.windows.net /TargetDatabaseName:<database> \
/TargetUser:<user> /TargetPassword:"$SQLPACKAGE_PASSWORD" \
/p:BlockOnPossibleDataLoss=true /p:DropObjectsNotInSource=false/p:DatabaseEdition/p:DatabaseServiceObjective| 操作 | 方向 | 默认内容 | 文件 |
|---|---|---|---|
| Extract | 数据库到文件 | 仅 schema | 写入 |
| Publish | 文件到数据库 | 仅 schema | 读取 |
| Export | 数据库到文件 | schema 和每个 base table 的数据行 | 写入 |
| Import | 文件到数据库 | schema 和每个 base table 的数据行 | 读取 |
Extract:
bash
sqlpackage /Action:Extract /TargetFile:app.dacpac /DiagnosticsFile:extract.log \
/SourceServerName:your-server.database.windows.net /SourceDatabaseName:<database> \
/SourceUser:<user> /SourcePassword:"$SQLPACKAGE_PASSWORD" \
/p:ExtractAllTableData=false /p:VerifyExtraction=trueExport:
bash
sqlpackage /Action:Export /TargetFile:app.bacpac /DiagnosticsFile:export.log \
/SourceServerName:your-server.database.windows.net /SourceDatabaseName:<database> \
/SourceUser:<user> /SourcePassword:"$SQLPACKAGE_PASSWORD" \
/p:VerifyExtraction=true /p:LongRunningCommandTimeout=0Import:
bash
sqlpackage /Action:Import /SourceFile:app.bacpac /DiagnosticsFile:import.log \
/TargetServerName:your-server.database.windows.net /TargetDatabaseName:<new-database> \
/TargetUser:<user> /TargetPassword:"$SQLPACKAGE_PASSWORD" \
/p:DatabaseEdition=Standard /p:DatabaseServiceObjective=S1Publish:
bash
sqlpackage /Action:Publish /SourceFile:app.dacpac \
/TargetServerName:your-server.database.windows.net /TargetDatabaseName:<database> \
/TargetUser:<user> /TargetPassword:"$SQLPACKAGE_PASSWORD" \
/p:BlockOnPossibleDataLoss=true /p:DropObjectsNotInSource=false/p:DatabaseEdition/p:DatabaseServiceObjectiveBoth Import and Publish can create the target; only Publish can rerun
Import 和 Publish 都能创建目标,但只有 Publish 可以重复运行
Microsoft Learn states it for each. Publish: if the database doesn't exist on the server, the
publish operation creates it, otherwise an existing database is updated. Import: a new database
can be created by the import action when the authenticated user has create database permissions.
On a logical server both need that permission to create the target: the server admin, or a member
of the role in .
dbmanagermasterWhat Import will not do is load into a target that already holds a user object:
text
Error SQL71659: Data cannot be imported into target because it contains one or more user objects.It refuses before any statement runs against the target, and retrying the same Import against the
same name refuses again, every time, until that database is dropped and recreated or a new name is
chosen. Publish diffs instead: rerun it against a target it already published to and it reports
with nothing to apply.
Update completeMicrosoft Learn 分别说明了这一点。Publish:如果服务器上不存在该数据库,publish 操作会创建它;否则会更新现有数据库。Import:当已认证用户拥有创建数据库权限时,import 操作可以创建新数据库。在逻辑服务器上,两者创建目标都需要该权限:服务器管理员,或 中 角色的成员。
masterdbmanagerImport 不会将数据加载到已包含用户对象的目标中:
text
Error SQL71659: Data cannot be imported into target because it contains one or more user objects.它会在任何语句针对目标运行之前就拒绝该操作;使用同一名称重试同一个 Import 也始终会再次被拒绝,除非删除并重新创建该数据库,或者选择新名称。相比之下,Publish 会执行差异分析:针对已发布过的目标再次运行它时,它会报告 ,且没有需要应用的内容。
Update completeThe property decides what is in the file, not the extension
决定文件内容的是属性,而不是扩展名
An Extract of a database with one table and one view produces a carrying no data entry
of any kind, and an Export of the same database produces a carrying
, one entry per base table holding rows.
.dacpac.bacpacData/dbo.Widget/TableData-000-00000.BCPThen the same Extract with one property added:
bash
sqlpackage /Action:Extract /TargetFile:app-with-data.dacpac \
/SourceServerName:your-server.database.windows.net /SourceDatabaseName:<database> \
/SourceUser:<user> /SourcePassword:"$SQLPACKAGE_PASSWORD" /p:ExtractAllTableData=trueThat file is still named , is still the output of Extract, and now carries
as well. is the narrower form, accepted
by both Extract and Export, naming one table per occurrence:
.dacpacData/dbo.Widget/TableData-000-00000.BCP/p:TableDatabash
sqlpackage /Action:Extract /TargetFile:app-two-tables.dacpac \
/SourceServerName:your-server.database.windows.net /SourceDatabaseName:<database> \
/SourceUser:<user> /SourcePassword:"$SQLPACKAGE_PASSWORD" \
/p:TableData=dbo.Widget /p:TableData=dbo.WidgetAuditOpen the file and look rather than reading the name:
bash
unzip -l app-with-data.dacpac对一个包含一张表和一个视图的数据库执行 Extract,会生成不含任何数据条目的 ;对同一个数据库执行 Export,则会生成 ,其中包含 ,每个包含数据行的 base table 对应一个条目。
.dacpac.bacpacData/dbo.Widget/TableData-000-00000.BCP然后,为同一个 Extract 添加一个属性:
bash
sqlpackage /Action:Extract /TargetFile:app-with-data.dacpac \
/SourceServerName:your-server.database.windows.net /SourceDatabaseName:<database> \
/SourceUser:<user> /SourcePassword:"$SQLPACKAGE_PASSWORD" /p:ExtractAllTableData=true该文件仍以 命名,仍然是 Extract 的输出,但现在也包含 。 是一种范围更窄的形式,Extract 和 Export 都接受它;每次出现用于指定一张表:
.dacpacData/dbo.Widget/TableData-000-00000.BCP/p:TableDatabash
sqlpackage /Action:Extract /TargetFile:app-two-tables.dacpac \
/SourceServerName:your-server.database.windows.net /SourceDatabaseName:<database> \
/SourceUser:<user> /SourcePassword:"$SQLPACKAGE_PASSWORD" \
/p:TableData=dbo.Widget /p:TableData=dbo.WidgetAudit打开文件查看,不要只根据名称判断:
bash
unzip -l app-with-data.dacpacAn export is not a backup, and is not consistent by default
Export 不是备份,默认也不具备一致性
Microsoft Learn states plainly that bacpac files aren't intended to be used for backup and restore
operations. On Azure SQL Database returns ,
and there is no RESTORE either.
BACKUP DATABASE app TO DISK='/tmp/x.bak'Msg 40510Learn again, on Export: for an export to be transactionally consistent, either no write activity is
occurring during the export, or the export is taken from a transactionally consistent copy of the
database. Nothing in the output of a successful export says which of those was true. Export from a
database copy, or from a database nothing is writing to, or state in the answer that the file may
be internally inconsistent.
Microsoft Learn 明确指出,bacpac 文件并非用于备份和还原操作。在 Azure SQL Database 上, 会返回 ,并且也不支持 RESTORE。
BACKUP DATABASE app TO DISK='/tmp/x.bak'Msg 40510Microsoft Learn 在 Export 文档中再次说明:要使导出具备事务一致性,导出期间必须没有 write activity,或者必须从事务一致的数据库副本执行导出。成功导出的输出中没有任何信息能表明实际满足的是哪一种。应从数据库副本导出,或从没有写入活动的数据库导出;否则应在回答中说明该文件可能存在内部不一致。
Before an Export or Extract from a database with operating history
对具有运行历史的数据库执行 Export 或 Extract 前
Export is limited to the Azure SQL Database surface area, so a source carrying an element outside
it fails with after the whole schema model has already been built, discarding the entire
attempt rather than the one object. The usual carriers are Windows-authenticated users and logins,
such as an inherited , and leftover Service Broker or query notification
permissions, most often a grant on .
SQL71627NT AUTHORITY\SYSTEMRECEIVEQueryNotificationErrorsQueueOpen references/preflight-and-sql71627.md before running an
export against a database you did not create yourself: it holds the queries that find both classes
and the remediation for each.
Extract accepts two properties that drop the offending model elements, and Export accepts neither:
bash
sqlpackage /Action:Extract /TargetFile:app.dacpac \
/SourceServerName:your-server.database.windows.net /SourceDatabaseName:<database> \
/SourceUser:<user> /SourcePassword:"$SQLPACKAGE_PASSWORD" \
/p:IgnoreUserLoginMappings=true /p:IgnorePermissions=trueSo when a database will not export, extracting the schema and moving the rows separately is the
route that still runs.
Export 仅适用于 Azure SQL Database 的功能范围,因此,如果源中包含该范围之外的元素,就会在完整的 schema model 构建完成后报 ;失败时丢弃的是整个尝试,而不是仅丢弃该对象。常见来源包括采用 Windows 身份验证的用户和 login,例如继承而来的 ;以及残留的 Service Broker 或 query notification 权限,后者最常见的是对 的 授权。
SQL71627NT AUTHORITY\SYSTEMQueryNotificationErrorsQueueRECEIVE在对自己并非创建的数据库运行 Export 之前,请打开 预检查与 SQL71627:其中包含用于查找这两类问题的查询,以及各自的修复方法。
Extract 接受两个用于移除有问题的 model 元素的属性,而 Export 均不接受:
bash
sqlpackage /Action:Extract /TargetFile:app.dacpac \
/SourceServerName:your-server.database.windows.net /SourceDatabaseName:<database> \
/SourceUser:<user> /SourcePassword:"$SQLPACKAGE_PASSWORD" \
/p:IgnoreUserLoginMappings=true /p:IgnorePermissions=true因此,当数据库无法 Export 时,提取 schema 并单独迁移数据行仍是可行的处理方式。
Read the plan before a Publish that could drop something
在可能删除内容的 Publish 之前先查看计划
DeployReport writes XML and Script writes T-SQL. Neither one changes the target database.
bash
sqlpackage /Action:DeployReport /SourceFile:app.dacpac /DeployReportPath:deploy-report.xml \
/TargetServerName:your-server.database.windows.net /TargetDatabaseName:<database> \
/TargetUser:<user> /TargetPassword:"$SQLPACKAGE_PASSWORD"bash
sqlpackage /Action:Script /SourceFile:app.dacpac /DeployScriptPath:publish.sql \
/TargetServerName:your-server.database.windows.net /TargetDatabaseName:<database> \
/TargetUser:<user> /TargetPassword:"$SQLPACKAGE_PASSWORD"/p:BlockOnPossibleDataLoss/p:CreateNewDatabase=trueDeployReport 会写出 XML,Script 会生成 T-SQL。两者都不会更改目标数据库。
bash
sqlpackage /Action:DeployReport /SourceFile:app.dacpac /DeployReportPath:deploy-report.xml \
/TargetServerName:your-server.database.windows.net /TargetDatabaseName:<database> \
/TargetUser:<user> /TargetPassword:"$SQLPACKAGE_PASSWORD"bash
sqlpackage /Action:Script /SourceFile:app.dacpac /DeployScriptPath:publish.sql \
/TargetServerName:your-server.database.windows.net /TargetDatabaseName:<database> \
/TargetUser:<user> /TargetPassword:"$SQLPACKAGE_PASSWORD"/p:BlockOnPossibleDataLoss/p:CreateNewDatabase=trueA vector index breaks the round trip, and the export looks fine
向量索引会破坏往返迁移,而 Export 看起来却正常
Check before planning anything around a bacpac:
sql
SELECT OBJECT_NAME(object_id) AS table_name, name
FROM sys.indexes WHERE type_desc = 'VECTOR';An import creates schema objects before it loads data, so a vector index is created against an
empty table. A vector index needs at least 100 rows carrying non-null vectors; with fewer, its
creation is refused with . Drop the vector indexes
before exporting and recreate them after the data is loaded. is refused while a
vector index exists (), so reloading in place hits the same wall one step earlier.
Msg 42266TRUNCATE TABLEMsg 42232围绕 bacpac 制定任何方案之前,先检查:
sql
SELECT OBJECT_NAME(object_id) AS table_name, name
FROM sys.indexes WHERE type_desc = 'VECTOR';Import 会先创建 schema 对象,再加载数据,因此 vector index 会在空表上创建。vector index 至少需要 100 行带有非 null vector 的数据;行数不足时,其创建会因 被拒绝。Export 前应删除 vector index,并在数据加载后重新创建。存在 vector index 时, 会因 被拒绝,因此原地 Reload 会在更早一步遇到同样的障碍。
Msg 42266TRUNCATE TABLEMsg 42232Check it worked
检查是否成功
Exit code 0 says the action SqlPackage attempted finished. It does not say the rows arrived.
bash
unzip -l app.bacpac | grep TableDataExpect one entry per base table that held rows, and
none for a view. Then compare the target against the source:
Data/<schema>.<table>/TableData-000-00000.BCPsql
SELECT SUM(p.rows) AS row_count, COUNT(DISTINCT t.object_id) AS table_count
FROM sys.tables AS t
JOIN sys.partitions AS p ON p.object_id = t.object_id AND p.index_id IN (0, 1);Run it on both databases. Equal numbers, or a stated reason they differ, is the check. A schema
only dacpac publishes to zero rows and that is correct, not a failure.
退出代码 0 表示 SqlPackage 尝试执行的操作已完成,并不表示数据行已经到达目标。
bash
unzip -l app.bacpac | grep TableData对于每个包含数据行的 base table,应存在一个 条目;视图则不应有对应条目。然后将目标与源进行比较:
Data/<schema>.<table>/TableData-000-00000.BCPsql
SELECT SUM(p.rows) AS row_count, COUNT(DISTINCT t.object_id) AS table_count
FROM sys.tables AS t
JOIN sys.partitions AS p ON p.object_id = t.object_id AND p.index_id IN (0, 1);在两个数据库上分别运行。数字相同,或明确说明数字为何不同,即视为检查通过。仅含 schema 的 dacpac 发布后为零行是正确结果,并非失败。
References
参考资料
- File listings, exit codes and the commands behind them: open it when a claim above disagrees with what you are seeing, or to rerun a check.
- The SQL71627 pre-flight scan
- The property reference per action, and the only authority on whether a property exists: Extract, Export, Import, Publish, Script and DeployReport.