SQL Server ':setvar' Error

SqlSql ServerTsql

Sql Problem Overview


I am trying to create some script variables in T-SQL as follows:

    /*
    Deployment script for MesProduction_Preloaded_KLM_MesSap
    */
    
    GO
    SET ANSI_NULLS, ANSI_PADDING, ANSI_WARNINGS, ARITHABORT, CONCAT_NULL_YIELDS_NULL, QUOTED_IDENTIFIER ON;
    
    SET NUMERIC_ROUNDABORT OFF;
    
    
    GO
    :setvar DatabaseName "MesProduction_Preloaded_KLM_MesSap"

However, when I run this, I get an error stating 'Incorrect syntax near ':'. What am I doing wrong?

Sql Solutions


Solution 1 - Sql

The :setvar only works in SQL command mode, so you are possibly within normal SQL execution in the management studio and have not swapped to command mode.

This can be done through the user interface in SQL Server Management Studio by going to the "Query" menu, and selecting "SQLCMD mode."

Solution 2 - Sql

Just enable sqlcmd mode in SQL Server Management Studio as described in following image.

enter image description here

Solution 3 - Sql

FOR SQL2012:

go to : tools/options/Query Execution and check the by default, open new queries in SQLCMD mode.

Hit the New Query button and make sure the variable definitions are highlighted, your script should run correctly now.

Previous versions:

http://blog.sqlauthority.com/2013/06/28/sql-server-how-to-set-variable-and-use-variable-in-sqlcmd-mode/

Solution 4 - Sql

try replacing :setvar DatabaseName "MesProduction_Preloaded_KLM_MesSap"

with:

USE [MesProduction_Preloaded_KLM_MesSap]
GO

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRandy MinderView Question on Stackoverflow
Solution 1 - SqlAndrewView Answer on Stackoverflow
Solution 2 - SqlMuhammad AwaisView Answer on Stackoverflow
Solution 3 - SqlTerrence Harry HolmesView Answer on Stackoverflow
Solution 4 - SqlKM.View Answer on Stackoverflow