Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server ':setvar' Error

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?

like image 392
Randy Minder Avatar asked Oct 14 '22 20:10

Randy Minder


People also ask

What is Setvar SQL?

The setvar command is used to define scripting variables. Variables that are defined by using the setvar command are stored internally. Scripting variables should not be confused with environment variables that are defined at the command prompt by using SET.

How do I DECLARE a variable in sqlcmd?

We can define variables implicitly by using the –v switch of sqlcmd. Also we can define and assign a value to variables explicitly using the :setvar sqlcmd command. When you define a variable implicitly you must add the variable name after the –v switch, followed with an equal sign and the desired value.


2 Answers

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

like image 272
Andrew Avatar answered Oct 17 '22 09:10

Andrew


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

enter image description here

like image 21
Muhammad Awais Avatar answered Oct 17 '22 08:10

Muhammad Awais