简体   繁体   English

SQL中附近的语法不正确

[英]Incorrect syntax near in SQL

I spend lot of time to figure out, what is the error, 我花了很多时间找出错误所在,

l have code like this. 我有这样的代码。

DECLARE @GeofenceName nvarchar(50) = '';
DECLARE @sql AS NVARCHAR(MAX)

SET @sql = N'select * from GeofenceMaster where GeofenceName = GName'

EXEC sp_executesql @sql,N'GName nvarchar(50)',@GeofenceName

PRINT @sql

it throw a error like this. 它会抛出这样的错误。

Msg 102, Level 15, State 1, Line 1 Incorrect syntax near 'GName'. 消息102,级别15,状态1,第1行'GName'附近的语法不正确。 select * from GeofenceMaster where GeofenceName = GName 从GeofenceMaster中选择*,其中GeofenceName = GName

anybody know which cause this problem? 有人知道造成这个问题的原因吗?

UPDATE : 更新

The original answer is incorrect. 原始答案不正确。 No parentheses should be required. 不需要括号。 See http://msdn.microsoft.com/en-us/library/ms188001(v=sql.105).aspx 参见http://msdn.microsoft.com/zh-cn/library/ms188001(v=sql.105).aspx

New answer 新答案

Try 尝试

DECLARE @GeofenceName nvarchar(50) = '';

DECLARE @sql AS NVARCHAR(MAX)

set @sql = N'select * from GeofenceMaster where GeofenceName = @GName'

EXEC sp_executesql @sql,N'GName nvarchar(50)',@GName=@GeofenceName

I've amended the SQL itself, ... = GName becomes ... = @GName and the execution, ..., @GeofenceName becomes ..., @GName = @GeofenceName . 我已经修改了SQL本身, ... = GName变为... = @GName ,而执行, ..., @GeofenceName变为..., @GName = @GeofenceName

Original answer 原始答案

You need to add some brackets. 您需要添加一些括号。

Instead of 代替

EXEC sp_executesql @sql,N'GName nvarchar(50)',@GeofenceName

Try 尝试

EXEC sp_executesql(@sql,N'GName nvarchar(50)',@GeofenceName)

the problem is in the variable "GName" (should have @, in this case would @GName), try with the following code, this works perfectly (for more info, see this LINK ): 问题出在变量“ GName”中(应该有@,在这种情况下为@GName),请尝试使用以下代码,这可以正常工作(有关更多信息,请参见此LINK ):

DECLARE @sql AS NVARCHAR(MAX)
declare @GName AS nvarchar(50) = ''

SET @sql = N'select * from GeofenceMaster where GeofenceName = ''' + @GName + ''''

EXEC sp_executesql @sql,N'@GName nvarchar(50)',GName

PRINT @sql

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM