在sql postdeployment构建脚本中使用变量?

Stu*_*rla 6 sql msbuild sqlcmd database-project

我希望能够做的是能够在Visual Studio数据库项目中创建一个定义变量的publising xml脚本,该脚本将用于编写脚本.

我的问题是我得到一个错误:"SQL72008:未定义变量DeployType." 如果我没有在后部署脚本中定义变量,就像这样":setvar DeployType"varchar(100)"

当我运行publish.xml时,DeployType参数正确地设置在生成的脚本的顶部但是该值被":setvar DeployType"varchar(100)覆盖.所以为了使这项工作,我需要手动删除运行此脚本之前的行.

所以问题是如何在没有在postdeployment脚本中默认setvar变量的情况下让项目构建并能够发布?

在此输入图像描述

这是我的PostDeployment.sql文件的内容,它不会在没有默认DeployType变量的情况下构建

--The line causing my problems. I would like to skip it somehow.
:setvar DeployType "varchar(100)"

Print 'Always include core'
:r ..\Data\Core\_BaseCore.sql

--Conditionaly add based on DeployType comming from the publishing.xml
IF ('$(DeployType)' = 'A')
BEGIN
:r ..\Data\A\_BaseKnap.sql
END
ELSE IF ('$(DeployType)' = 'B')
BEGIN
:r ..\Data\B\_BaseB.sql
END
Run Code Online (Sandbox Code Playgroud)

这是Database.publish.xml文件中的内容

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
 <PropertyGroup>
   <IncludeCompositeObjects>True</IncludeCompositeObjects>
   <TargetDatabaseName>db name</TargetDatabaseName>
   <DeployScriptFileName>Database.sql</DeployScriptFileName>
   <ProfileVersionNumber>1</ProfileVersionNumber>
   <TargetConnectionString>Connection string</TargetConnectionString>
 </PropertyGroup>
 <ItemGroup>
   <SqlCmdVariable Include="DeployType">
     <Value>B</Value>
   </SqlCmdVariable>
 </ItemGroup>
</Project>
Run Code Online (Sandbox Code Playgroud)

当我将其发布到脚本文件时,这是生成的脚本要针对我得到的数据库运行(不需要删除大量内容).

:setvar DeployType "B"

--This nulls out the DeployType set before
:setvar DeployType "varchar(100)"

Print 'Always include core'
:r ..\Data\Core\_BaseCore.sql

--Conditionaly add based on DeployType comming from the publishing.xml
IF ('$(DeployType)' = 'A')
BEGIN
:r ..\Data\A\_BaseKnap.sql
END
ELSE IF ('$(DeployType)' = 'B')
BEGIN
:r ..\Data\B\_BaseB.sql
END
Run Code Online (Sandbox Code Playgroud)

并运行此(在例如Sql Manager中)结果是

Print 'Always include core'
Run Code Online (Sandbox Code Playgroud)

它没有进入IF语句,因为它已被默认.

希望这很清楚.

Ale*_*x M 15

我知道这是一个有点旧的线程,但这里是答案:

单击数据库项目上的属性,然后导航到"SQLCMD变量"窗口.$(DeployType)在SQLCMD变量表中定义变量.这将允许项目编译,因此您可以(并且实际需要):setvar DeployType "varchar(100)"从脚本本身中删除该行.在此输入图像描述