I am trying to perform an SQL query using Invoke-SqlCmd
launching script as inputfile which contains SQLCMD variables, as $(varPROJECTNAME).
For example:
CREATE DATABASE [$(varPROJECTNAME)$(varDBNAME)]
In such a case, i want to be able to set an empty string as varPROJECTNAME
value.
This request will run successfully with classical SQLCMD tool, but with Invoke-SqlCmd, i get error, script variable varPROJECTNAME is undefined.
Invoke-Sqlcmd -Username $LoginSQL -Password $PasswordSQL -ServerInstance $InstanceSQL -Verbose -InputFile "$rootPackage\DB\UpdateDB\00-initSql\00-SubsTechCreateDatabase.sql" -Variable "varPROJECTNAME=$projectName","varDBNAME=$DatabaseName"
In case above, if $projectName=""
, There will be an error
Is it possible to set a default value calling Invoke-SqlCmd, or from sql script point of view, assign a default value to the variable when it's undefined?
Many thanks in advance for your help
sqlcmd.exe
doesn't like it if you do that either:sqlcmd -Q "SELECT '$(var)'"
->"'var' scripting variable not defined."
It will then proceed anyway, leaving the variable without any substitution, literally as$(var)
(unless you pass-b
, then the batch is aborted and nothing happens, in the same manner asInvoke-SqlCmd
). Relying on this is ill-advised. If you must do this, I recommend identifying the variables and explicitly passing empty values anyway. – Jeroen Mostertinvoke-sqlcmd 'SELECT $(var)' -Variable "var=''"
-> no error. You'll have to supply code that fails. – Jeroen Mostert