Check for SQLCMD mode and exit otherwise

Stephen Hulbert 41 Reputation points
2022-03-04T14:50:46.613+00:00

We have a problem with DEV's running SQLCMD scripts in SSMS without SQLCMD mode turned on.

Code like this (but not this, obvs):

use PRODUCTION  
  
:`setvar CurrentDatabase "DEVELOPMENT"  
  
use [$(CurrentDatabase)]  
truncate table Business.CriticalData  

What I'd like is for a check to be made against SQLCMD mode, and the script terminated if it's not running.
Reading around, it seems no implementation of the following metacode is supported:

if @SQLCMDMODE = 0   
exit  

All of the solutions seem to rely on the user being an admin and don't work if they're not.

E.g. "RAISERROR 20" and "set noexec on"

This is such a fundamental requirement.

Is there really no way to do it?

Developer technologies Transact-SQL
SQL Server Other
0 comments No comments
{count} votes

Accepted answer
  1. Tom Phillips 17,771 Reputation points
    2022-03-04T15:15:57.37+00:00

    Because this is an SSMS option, not a TSQL option, you cannot directly test for it.

    Please see:
    https://jonlabelle.com/snippets/view/sql/check-if-sql-command-mode-is-enabled

    0 comments No comments

3 additional answers

Sort by: Most helpful
  1. Stephen Hulbert 41 Reputation points
    2022-03-04T15:47:49.077+00:00

    That does not work if you're not an admin.

    Or, it just doesn't work at all.

    This is so simple and necessary, there must be something in a bigger picture.


  2. Stephen Hulbert 41 Reputation points
    2022-03-04T16:00:53.19+00:00

    Further, since the whole script is pre-parsed by SSMS, why does it allow the script to run AT ALL if it's got SQLCMD syntax in it?


  3. Christopher 0 Reputation points
    2023-07-27T12:19:39.92+00:00

    SSDT does this via this bit for publish scripts:

    :setvar __IsSqlCmdEnabled "True"
    GO
    IF N'$(__IsSqlCmdEnabled)' NOT LIKE N'True'
        BEGIN
            PRINT N'SQLCMD mode must be enabled to successfully execute this script.';
            SET NOEXEC ON;
        END
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.