MS SQL例外:“@ P0”附近的语法错误

我查询使用MS SQL的数据库,出于某种原因,我得到了以下错误: com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near '@P0'即使这个'P0'不是我的语法中的任何地方。 ..

我读过有人遇到同样的问题,但他们正在使用存储过程,这是我没有使用的东西,所以我不明白他的解决scheme将如何为我工作。 (他的解决scheme是在程序调用周围添加大括号。

无论如何,下面我已经粘贴了相关的代码。 真的希望有人可以帮助我,让人相当沮丧。

 PreparedStatement stmt = null; Connection conn = null; String sqlQuery = "SELECT TOP ? \n"+ "z.bankAccountNo, \n"+ "z.statementNo, \n"+ "z.transactionDate, \n"+ "z.description, \n"+ "z.amount, \n"+ "z.guid \n"+ "FROM \n"+ "( \n"+ "select \n"+ "ROW_NUMBER() OVER (ORDER BY x.transactionDate, x.statementNo) AS RowNumber, \n"+ "x.transactionDate, \n"+ "x.statementNo, \n"+ "x.description, \n"+ "x.amount, \n"+ "x.bankAccountNo, \n"+ "x.guid \n"+ "FROM \n"+ "( \n"+ "SELECT \n"+ "a.bankAccountNo, \n"+ "a.statementNo, \n"+ "a.transactionDate, \n"+ "a.description, \n"+ "a.amount, \n"+ "a.guid \n"+ "FROM BankTransactions as a \n"+ "LEFT OUTER JOIN BankTransactionCategories as b \n"+ "ON a.category = b.categoryCode \n"+ "WHERE b.categoryCode is null \n"+ ") as x \n"+ ") as z \n"+ "WHERE (z.RowNumber >= ?)"; stmt = conn.prepareStatement(sqlQuery); stmt.setInt(1, RowCountToDisplay); stmt.setInt(2, StartIndex); ResultSet rs = null; try{ rs = stmt.executeQuery(); } catch (Exception Error){ System.out.println("Error: "+Error); } 

提前致谢!

如果你传入一个variables,SQL Server要求你将括号放在参数的top

 SELECT TOP (?) 

在我们的应用程序中,我们扩展了一个depraceted的SQLServerDialect 。 改成SQLServer2008Dialect ,问题就消失了。

升级hibernate到版本5.x并遇到此问题。 不得不将org.hibernate.dialect.SQLServerDialect中的“hibernate.dialect”configuration更新为org.hibernate.dialect.SQLServer2012Dialect。 修正了这个问题!

Hibernate文档参考: https : //docs.jboss.org/hibernate/orm/3.6/reference/en-US/html/session-configuration.html#configuration-programmatic

Hibernate Jira问题: https : //hibernate.atlassian.net/browse/HHH-10032

这也可能是由于SQL中的语法错误导致的

 select * from drivel d where exists (select * from drivel where d.id = drivel.id and drivel.start_date < '2015-02-05' AND '2015-02-05' < drivel.end_date) OR exists (select * from drivel where d.id = drivel.id and drivel.start_date < '2015-02-05' AND '2015-02-05' < drivel.end_date) OR exists (select * from drivel where d.id = drivel.id and '2015-02-05' < drivel.start_date and drivel.end_date < '2015-02-05' 

给了这个消息

com.microsoft.sqlserver.jdbc.SQLServerException:“@ P5”附近的语法错误

问题实际上是最后缺失的平衡'),即正确的版本

 select * from drivel d where exists (select * from drivel where d.id = drivel.id and drivel.start_date < '2015-02-05' AND '2015-02-05' < drivel.end_date) OR exists (select * from drivel where d.id = drivel.id and drivel.start_date < '2015-02-05' AND '2015-02-05' < drivel.end_date) OR exists (select * from drivel where d.id = drivel.id and '2015-02-05' < drivel.start_date and drivel.end_date < '2015-02-05')