What I would like to be able to do, is to be able to create a publising xml script in Visual Studio database project that defines a variable, that will be used to compose a script.
My problem is that I get a Error: "SQL72008: Variable DeployType is not defined." if I don´t define the variable in the post deployment script like this ":setvar DeployType "varchar(100)"
When I run the publish.xml the DeployType parameter is rightly set at the top of the generated script BUT that value get overridden with the ":setvar DeployType "varchar(100)". So to make this work I would need to manually remove that line before running this script.
So the question is How can I let the project build and be able to publish without defaulting the setvar variable in the postdeployment script?
This is the content of my PostDeployment.sql file that does not build without defaulting the DeployType variable
--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
This is the content in the Database.publish.xml file
<?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>
When I publish this to a script file this is the generated script to be run against the database I get (lots of stuff removed not needed).
: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
And running this (in e.g Sql Manager) the result is
Print 'Always include core'
where it doesn't go into the IF statements because it has been defaulted.
Hope this is clear enough.
I know this is a bit old thread, but here is the answer:
Click the properties on you database project and navigate to the "SQLCMD Variables" window. Define your $(DeployType)
variable in the SQLCMD Variables table. This will allow the project to compile and hence you can (and actually need) remove the line :setvar DeployType "varchar(100)"
from the script itself.
来源:https://stackoverflow.com/questions/26178189/using-variable-in-sql-postdeployment-build-script