【问题标题】:Incorrect syntax near in SQLSQL中附近的语法不正确
【发布时间】:2013-05-30 17:31:01
【问题描述】:

我花了很多时间弄清楚,错误是什么,

我有这样的代码。

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

它会抛出这样的错误。

消息 102,级别 15,状态 1,第 1 行“GName”附近的语法不正确。 select * from GeofenceMaster where GeofenceName = GName

有人知道导致这个问题的原因吗?

【问题讨论】:

  • 你希望参数N'GName nvarchar(50)'@GeofenceName做什么?

标签: sql sql-server tsql dynamic-sql


【解决方案1】:

更新

原来的答案不正确。不需要括号。见http://msdn.microsoft.com/en-us/library/ms188001(v=sql.105).aspx

新答案

试试

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

我已经修改了 SQL 本身,... = GName 变成了... = @GName 并且执行,..., @GeofenceName 变成了..., @GName = @GeofenceName

原答案

你需要添加一些括号。

代替

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

试试

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

【讨论】:

  • 好吧,正式名称是paratheses,但是是的,必须使用字符() 来分隔存储过程的参数。
【解决方案2】:

问题出在变量“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

【讨论】:

  • @ 是必须的,我可以在哪里提供文档。
  • 嗨BalaKrishnan웃,不太理解你的问题,但是如果你需要文档,请到这里support.microsoft.com/kb/262499 在这个页面上有两个完美的例子,请复制粘贴并帮助你理解方法“sp_executesql”
猜你喜欢
  • 1970-01-01
  • 2017-02-07
  • 2018-06-26
  • 2016-10-22
  • 2017-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多