SQL Server ':setvar' 错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2684997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 06:02:49  来源:igfitidea点击:

SQL Server ':setvar' Error

sqlsql-servertsql

提问by Randy Minder

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

我正在尝试在 T-SQL 中创建一些脚本变量,如下所示:

    /*
    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?

但是,当我运行它时,我收到一条错误消息,指出“':'附近的语法不正确。我究竟做错了什么?

回答by Andrew

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.

:setvar 仅适用于 SQL 命令模式,因此您可能在 management studio 中正常执行 SQL 并且尚未切换到命令模式。

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

这可以通过 SQL Server Management Studio 中的用户界面通过转到“查询”菜单并选择“SQLCMD 模式”来完成。

回答by Muhammad Awais

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

只需在 SQL Server Management Studio 中启用 sqlcmd 模式,如下图所示。

enter image description here

在此处输入图片说明

回答by Terrence Harry Holmes

FOR SQL2012:

对于 SQL2012:

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

转到:工具/选项/查询执行并检查默认情况下,以 SQLCMD 模式打开新查询。

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

点击 New Query 按钮并确保突出显示变量定义,您的脚本现在应该可以正确运行。

Previous versions:

之前的版本:

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

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

回答by KM.

try replacing :setvar DatabaseName "MesProduction_Preloaded_KLM_MesSap"

尝试更换 :setvar DatabaseName "MesProduction_Preloaded_KLM_MesSap"

with:

和:

USE [MesProduction_Preloaded_KLM_MesSap]
GO