【问题标题】:SQL Server database project pre- and post-deployment scriptSQL Server 数据库项目部署前和部署后脚本
【发布时间】:2023-03-09 22:50:02
【问题描述】:

我已经在一个表中添加了一个额外的列,我想在部署后脚本中使用查询对其进行初始化。不幸的是,我似乎无法编写每次都可以运行的查询,因此我正在寻找一种方法来检查部署前脚本(如果该列可用)并将参数或变量传递给部署后脚本然后将运行一次初始化查询。

尝试 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

并在部署后脚本中访问它:

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

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

错误 SQL72014:.Net SqlClient 数据提供者:

消息 137,第 15 级,状态 2,第 12 行
必须声明标量变量“@PerformInitQuery”

【问题讨论】:

  • 普通变量不起作用,因为它只存在于单个批次中。部署将使用多个批次。只需检查创建脚本,您就会看到多个 GO 语句。为什么不将您在部署前所做的检查添加到部署后?
  • 因为构建会在部署后脚本运行之前创建列,所以我无法确定它是在本次运行还是之前运行

标签: sql sql-server visual-studio sql-server-data-tools database-project


【解决方案1】:

您可以尝试使用临时表来保存您希望从 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-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

你好世界

更新完成。

【讨论】:

  • 谢谢,这成功了!
猜你喜欢
  • 1970-01-01
  • 2011-06-14
  • 1970-01-01
  • 2014-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-11
相关资源
最近更新 更多