Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to automatically force SQLCMD mode in script?

Tags:

sql

ssms

sqlcmd

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).

like image 242
Nicolas Webb Avatar asked Aug 09 '10 15:08

Nicolas Webb


People also ask

How do I enable SQLCMD mode in a script?

Enable SQLCMD Scripting by Default To turn SQLCMD scripting on by default, on the Tools menu select Options, expand Query Execution, and SQL Server, click the General page, and then check the By default open new queries in SQLCMD Mode box.

How do I enable SQLCMD mode in management studio?

To enable SQLCMD mode, click the SQLCMD Mode option under the Query menu: Another way to enable the SQLCMD Mode is by using a combination of keys ALT+Q+M from the keyboard. In SSMS, there is an option to set the query windows to be opened in the SQLCMD mode by default.

Is SQLCMD installed by default?

Net SqlClient Data Provider.The SQLCMD utility is available by default under "C:\Program Files\Microsoft SQL Server\100\Tools\Binn\" location. To get a list of the different command options you can run SQLCMD -? at a command prompt as shown in the below snippet.


1 Answers

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
like image 182
Yahoo Serious Avatar answered Sep 28 '22 07:09

Yahoo Serious