SQL Server数据库项目部署前和部署后脚本

时间:2016-09-19 09:09:14

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

我已经在表中添加了一个额外的列,我希望使用后部署脚本中的查询进行初始化。不幸的是,我似乎无法编写一个可以每次运行的查询,所以如果列可用并且将参数或变量传递给帖子,我正在寻找检查预部署脚本的方法。 -deployment脚本,然后运行一次初始化查询。

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

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数据提供程序:

     

Msg 137,Level 15,State 2,Line 12
  必须声明标量变量" @ PerformInitQuery"

1 个答案:

答案 0 :(得分:3)

您可以尝试使用临时表来保存您希望从前脚本传递到后脚本的值;

/*
     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
  

你好世界

     

更新完成。