gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 13:41:44 25 4
gpt4 key购买 nike

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

尝试 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 文件发布到数据库。

Error SQL72014: .Net SqlClient Data Provider:

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

最佳答案

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

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

hello world

Update complete.

关于SQL Server 数据库项目部署前和部署后脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39569341/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com