sqlpackage-import-export

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Move 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
sql-database-projects
. Azure SQL Database's own automated backups and point-in-time or geo-restore are
restore-and-recover
. Loading rows into a table that already exists is
bulk-load-and-bulk-copy
. Vector indexes themselves are
vector-search-azure-sql
.
本文负责决定如何将整个现有数据库作为可移植文件迁移的四种操作,并给出每种操作对应的命令行。从源代码管理的 SQL 项目构建 dacpac、通过 CI 交付该文件,以及处理它的 refactorlog 和部署前后脚本,均属于
sql-database-projects
。Azure SQL Database 自带的自动备份以及时间点还原或异地还原,属于
restore-and-recover
。向已经存在的表中加载数据行属于
bulk-load-and-bulk-copy
。向量索引本身属于
vector-search-azure-sql
。

Scope

范围

  • 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.
ExtractAllTableData
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:
bash
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:
/p:Storage=File
is the .NET Framework build's default, and Learn records
Memory
as the only option on the cross-platform build.
Every parameter in this skill is written in long form. The same help output gives each one a short form,
/Action
as
/a
,
/SourceFile
as
/sf
,
/TargetFile
as
/tf
, and the two forms are interchangeable.
属性因操作而异。
ExtractAllTableData
是 Extract 属性,Export 不接受。不存在一份覆盖所有操作的属性目录,因此应查询当前使用的版本:
bash
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.
某个属性也可能确实存在且有文档记录,却仍然无法使用:
/p:Storage=File
是 .NET Framework 版本的默认值,而 Microsoft Learn 将
Memory
记录为跨平台版本的唯一选项。
本 skill 中的每个参数均采用完整形式。同一份帮助输出还会给出每个参数的短形式,例如
/Action
对应
/a
、
/SourceFile
对应
/sf
、
/TargetFile
对应
/tf
,两种形式可以互换使用。

The four actions, as four commands

四种操作及对应命令

ActionDirectionDefault contentsFile
Extractdatabase to fileschema onlywrites
.dacpac
Publishfile to databaseschema onlyreads
.dacpac
Exportdatabase to fileschema and every base table's rowswrites
.bacpac
Importfile to databaseschema and every base table's rowsreads
.bacpac
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=true
Export:
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=0
Import:
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=S1
Publish:
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
and
/p:DatabaseServiceObjective
are accepted by Import and Publish and are how the database they create is sized. Extract and Export do not accept them.
操作方向默认内容文件
Extract数据库到文件仅 schema写入
.dacpac
Publish文件到数据库仅 schema读取
.dacpac
Export数据库到文件schema 和每个 base table 的数据行写入
.bacpac
Import文件到数据库schema 和每个 base table 的数据行读取
.bacpac
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=true
Export:
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=0
Import:
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=S1
Publish:
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
均可由 Import 和 Publish 接受,用于设置所创建数据库的大小。Extract 和 Export 不接受它们。

Both 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
dbmanager
role in
master
.
What 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
Update complete
with nothing to apply.
Microsoft Learn 分别说明了这一点。Publish:如果服务器上不存在该数据库,publish 操作会创建它;否则会更新现有数据库。Import:当已认证用户拥有创建数据库权限时,import 操作可以创建新数据库。在逻辑服务器上,两者创建目标都需要该权限:服务器管理员,或
master
中
dbmanager
角色的成员。
Import 不会将数据加载到已包含用户对象的目标中:
text
Error SQL71659: Data cannot be imported into target because it contains one or more user objects.
它会在任何语句针对目标运行之前就拒绝该操作;使用同一名称重试同一个 Import 也始终会再次被拒绝,除非删除并重新创建该数据库,或者选择新名称。相比之下,Publish 会执行差异分析:针对已发布过的目标再次运行它时,它会报告
Update complete
,且没有需要应用的内容。

The property decides what is in the file, not the extension

决定文件内容的是属性,而不是扩展名

An Extract of a database with one table and one view produces a
.dacpac
carrying no data entry of any kind, and an Export of the same database produces a
.bacpac
carrying
Data/dbo.Widget/TableData-000-00000.BCP
, one entry per base table holding rows.
Then 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=true
That file is still named
.dacpac
, is still the output of Extract, and now carries
Data/dbo.Widget/TableData-000-00000.BCP
as well.
/p:TableData
is the narrower form, accepted by both Extract and Export, naming one table per occurrence:
bash
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
Open the file and look rather than reading the name:
bash
unzip -l app-with-data.dacpac
对一个包含一张表和一个视图的数据库执行 Extract,会生成不含任何数据条目的
.dacpac
;对同一个数据库执行 Export,则会生成
.bacpac
,其中包含
Data/dbo.Widget/TableData-000-00000.BCP
,每个包含数据行的 base table 对应一个条目。
然后,为同一个 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
该文件仍以
.dacpac
命名,仍然是 Extract 的输出,但现在也包含
Data/dbo.Widget/TableData-000-00000.BCP
。
/p:TableData
是一种范围更窄的形式,Extract 和 Export 都接受它;每次出现用于指定一张表:
bash
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.dacpac

An 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
BACKUP DATABASE app TO DISK='/tmp/x.bak'
returns
Msg 40510
, and there is no RESTORE either.
Learn 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 上,
BACKUP DATABASE app TO DISK='/tmp/x.bak'
会返回
Msg 40510
,并且也不支持 RESTORE。
Microsoft 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
SQL71627
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
NT AUTHORITY\SYSTEM
, and leftover Service Broker or query notification permissions, most often a
RECEIVE
grant on
QueryNotificationErrorsQueue
.
Open 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=true
So 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 构建完成后报
SQL71627
;失败时丢弃的是整个尝试,而不是仅丢弃该对象。常见来源包括采用 Windows 身份验证的用户和 login,例如继承而来的
NT AUTHORITY\SYSTEM
;以及残留的 Service Broker 或 query notification 权限,后者最常见的是对
QueryNotificationErrorsQueue
的
RECEIVE
授权。
在对自己并非创建的数据库运行 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
defaults to True and is what stops a publish that would drop data. Leave it on.
/p:CreateNewDatabase=true
does not mean "create it if it is missing", which Publish already does: Learn describes it as whether the target database should be updated or whether it should be dropped and re-created. Setting it against a populated target destroys that target.
DeployReport 会写出 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
默认为 True,它会阻止可能丢失数据的 publish。请保持启用。
/p:CreateNewDatabase=true
的含义不是“缺少时创建”——Publish 本来就会这样做;Microsoft Learn 对它的说明是:更新目标数据库,还是将其删除并重新创建。对已有数据的目标设置该参数会销毁该目标。

A 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
Msg 42266
. Drop the vector indexes before exporting and recreate them after the data is loaded.
TRUNCATE TABLE
is refused while a vector index exists (
Msg 42232
), so reloading in place hits the same wall one step earlier.
围绕 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 的数据;行数不足时,其创建会因
Msg 42266
被拒绝。Export 前应删除 vector index,并在数据加载后重新创建。存在 vector index 时,
TRUNCATE TABLE
会因
Msg 42232
被拒绝,因此原地 Reload 会在更早一步遇到同样的障碍。

Check it worked

检查是否成功

Exit code 0 says the action SqlPackage attempted finished. It does not say the rows arrived.
bash
unzip -l app.bacpac | grep TableData
Expect one
Data/<schema>.<table>/TableData-000-00000.BCP
entry per base table that held rows, and none for a view. Then compare the target against the source:
sql
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.BCP
条目;视图则不应有对应条目。然后将目标与源进行比较:
sql
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.
  • 文件列表、退出代码及其对应命令:如果上述说法与实际观察不符,或需要重新运行检查,请打开此文档。
  • SQL71627 预检查扫描
  • 按操作区分的属性参考,也是判断属性是否存在的唯一权威来源: Extract、 Export、 Import、 Publish、 Script 和 DeployReport。