Search code examples
c#t-sqlvisual-studio-2012sqlcmd

Using SQLCMD variables in a condition


When publishing a new database, I want to run a procedure only if the server has SQL Agent installed.

Therefor, I created a new SQLCMD variable called $(SqlAgent) and I want to add a condition (instead of checking if SQLAgent runs in msdb.dbo.sysjobs cause sometimes it is installed but doesn't run).

And I add the following

 IF $(SqlAgent)='exists'
 BEGIN
EXEC [INFRA]....

 END

This fails because of

incorrect syntax next to SqlAgent

How can I use sqlcmd variable in a condition?


Solution

  • First of all, check if you are running your script window as sqlcmd. The try this instead

    IF ('$(SqlAgent)' = 'exists')
    Begin
        Exec ...
    End