Search code examples
sqlsqlcmdssms

Is it possible to automatically force SQLCMD mode in script?


We're using Visual Studio Database Professional and it makes heavy use of SQLCMD variables to differentiate between environments while deploying.

I know there's several directives available for setting context (like :connect for server name). Is there a way within the script itself to force SQLCMD mode for execution? Part of our deployment process is to have DBA's examine and execute the scripts and it would be a nice safety net (so I don't have to remind them to set their execution mode to SQLCMD).


Solution

  • Not a solution, but as a work-around, you could embed your script in some warning. This post inspired me to this code:

    SET NOEXEC OFF; -- previous execution may have toggled it
    :setvar IsSqlCmdEnabled "True"
    GO
    IF ('$(IsSqlCmdEnabled)' = '$' + '(IsSqlCmdEnabled)')
    BEGIN
      PRINT('Use SqlCmd-mode!!');
      SET NOEXEC ON;
      -- RAISERROR ('This script must be run in SQLCMD mode.', 20, 1) WITH LOG
    END
    ELSE
    BEGIN
      PRINT('Using SqlCmd-mode')
      -- insert the code you really want to execute:
      -- ...
    END
    SET NOEXEC OFF; -- do not disable next execution in this session