使用命令行导出 SQL Server 数据层应用程序

    xiaoxiao2022-07-02  108

    点击上方蓝字关注“汪宇杰博客”

    我们可以使用 SSMS 导出 SQL Server 数据库的数据层应用程序。我在本地机器上使用这种方法已经有好几年了。如果不知道什么是 DAC,您可以参考 Microsoft 文档:

    https://docs.microsoft.com/en-us/sql/relational-databases/data-tier-applications/data-tier-applications?view=sql-server-2017

    数据层应用程序 (DAC) 是一个逻辑数据库管理实体,用于定义与用户数据库关联的所有 SQL Server 对象,如表、视图和实例对象(包括登录名)。DAC 是 SQL Server 数据库部署的一个自包含单元,它使数据层开发人员和数据库管理员能够将 SQL Server 对象打包到一个名为“DAC 包”(也称作 DACPAC)的可移植项目中。

    但是,要跑在自动化环境下工作, 如 CI/CD 环境,或一些自动的计划任务。我们通常需要在命令行下完成。

    微软提供了一个跨平台的命令行工具, 可以导入/导出DAC: sqlpackage.exe

    它是用.NET写的,目前 Linux 和 macOS 的版本还在预览中。对于 Windows,可以在此处下载并安装:https://go.microsoft.com/fwlink/?linkid=2087429

    这个工具会被安装到 C:\Program Files\Microsoft SQL Server\150\DAC\bin 下面,但是它不会自动更改PATH环境变量,因此要使用这个工具得手工切换到安装目录。

    要导出数据层应用程序,需要指定3个参数:

    /Action:{Extract|DeployReport|DriftReport|Publish|Script|Export|Import} Specifies the action to be performed. (short form /a)

    /SourceConnectionString:<string>Specifies a valid SQL Server/Azure connection string to the source database. If this parameter is specified it shall be used exclusively of all other source parameters. (short form /scs)

    /TargetFile:<string> Specifies a target file (i.e., a .dacpac files) to be used as the target of action instead of a database. If this parameter is used, no other target parameter shall be valid. This parametershall be invalid for actions that only support database targets. (short form /tf)

    例如

    SqlPackage.exe /a:export /scs:"Server=(local);Database=moonglade-dev;Trusted_Connection=True;" /tf:"D:\moonglade-dev-20190520.bacpac"

    可以看到 bacpac 文件导出成功

    最新回复(0)