SQL 服务器数据库项目预和 post 部署脚本

SQL Server database project pre- and post-deployment script

我向 table 添加了一个额外的列,我想使用 post 部署脚本中的查询对其进行初始化。不幸的是,我似乎无法编写一个每次都可以是 运行 的查询,所以我正在寻找一种方法来检查预部署脚本是否该列可用并将参数或变量传递给 post-部署脚本,然后运行初始化查询一次。

尝试 1: 我尝试在预部署脚本中设置一个 sqlcmd 变量,但不允许使用以下语法:

IF COL_LENGTH('dbo.Table','NewColumn') IS NULL
    :setvar PerformInitQuery 1

尝试 2: 我也试过在预部署脚本中使用普通变量:

DECLARE @PerformInitQuery BIT = 0
IF COL_LENGTH('dbo.Table','NewColumn') IS NULL
    SET @PerformInitQuery = 1

并在 post-部署脚本中访问它:

IF @PerformInitQuery = 1
BEGIN
    :r ".\DeploymentScripts\PerformInitQuery.sql"
END

最后一次尝试似乎在从 Visual Studio 发布项目时有效,但在我们的构建服务器上无效;它使用 SqlPackage.exe 将生成的 .dacpac 文件发布到数据库。

Error SQL72014: .Net SqlClient Data Provider:

Msg 137, Level 15, State 2, Line 12
Must declare the scalar variable "@PerformInitQuery"

您可以尝试使用临时 table 来保存您希望从 pre 传递给 post 脚本的值;

/*
     Pre-Deployment Script Template                         
    --------------------------------------------------------------------------------------
     This file contains SQL statements that will be executed before the build script.   
     Use SQLCMD syntax to include a file in the pre-deployment script.          
     Example:      :r .\myfile.sql                              
     Use SQLCMD syntax to reference a variable in the pre-deployment script.        
     Example:      :setvar TableName MyTable                            
                   SELECT * FROM [$(TableName)]                 
    --------------------------------------------------------------------------------------
    */

    select 'hello world' as [Col] into #temptable

在 post 部署脚本中获取;

/*
Post-Deployment Script Template                         
--------------------------------------------------------------------------------------
 This file contains SQL statements that will be appended to the build script.       
 Use SQLCMD syntax to include a file in the post-deployment script.         
 Example:      :r .\myfile.sql                              
 Use SQLCMD syntax to reference a variable in the post-deployment script.       
 Example:      :setvar TableName MyTable                            
               SELECT * FROM [$(TableName)]                 
--------------------------------------------------------------------------------------
*/

declare @var nvarchar(200)
select @var = [Col] from #temptable

print @var

hello world

Update complete.