SQL Server ':setvar' Error

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

enter image description here


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/


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