java MS SQL异常:“@P0”附近的语法不正确

fbcarpbf  于 2023-01-01  发布在  Java
关注(0)|答案(7)|浏览(154)

我正在使用MS SQL查询数据库,由于某种原因,我得到以下错误:com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near '@P0',即使这个“P0”不在我的语法中...
我读到有人遇到过同样的问题,但他们使用的是存储过程,我没有使用,所以我不知道他的解决方案对我有什么用。(他的解决方案是在过程调用周围加上大括号{}。
不管怎样,下面我已经贴上了相关的代码。真的希望有人能帮我这个,得到相当沮丧。

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);
}
jhkqcmku

jhkqcmku1#

如果传入变量,SQL Server要求您在top的参数两边加上括号:

SELECT TOP (?)
oaxa6hgo

oaxa6hgo2#

在我们的应用程序中,我们扩展了一个被弃用的SQLServerDialect。在更改为SQLServer2008Dialect后,问题消失了。

4szc88ey

4szc88ey3#

将hib升级到5.x版本时遇到了这个问题。必须将“hib.dialect”配置从org. hib.dialect.SQLServerDialect更新为org. hib. dialect. SQLServer 2012 Dialect。修复了这个问题!
Hibernate文档参考:https://docs.jboss.org/hibernate/orm/3.6/reference/en-US/html/session-configuration.html#configuration-programmatic
休眠Jira问题:https://hibernate.atlassian.net/browse/HHH-10032

but5z9lq

but5z9lq4#

它也可能是由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'

传达了信息
服务器异常:“@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')
xuo3flqw

xuo3flqw5#

如果使用自定义数据源,则添加属性:

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.SQLServer2012Dialect

在www.example.com中application.properties将无法工作。
您必须将属性作为属性Map添加到数据源Bean中:

@Bean
public LocalContainerEntityManagerFactoryBean sqlServerEntityManagerFactory() {
    HashMap<String, String> properties = new HashMap<>();
    properties.put("hibernate.dialect", "org.hibernate.dialect.SQLServer2012Dialect");

    LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
    factoryBean.setDataSource(sqlServerDataSource());
    factoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
    factoryBean.setJpaPropertyMap(properties);
    return factoryBean;
}
r7xajy2e

r7xajy2e6#

如果您在spring-boot应用中使用Hibernate,则可以使用以下配置属性设置hibernate.dialect
spring.jpa.database-platform=org.hibernate.dialect.SQLServer2008Dialect

kyxcudwk

kyxcudwk7#

按以下方式调用过程

@Override
public List<Rep_Holdings> getHoldingsReport(
        int pid
)
{
    List<Rep_Holdings> holdings = null;

    Session sess = sFac.getCurrentSession();
    if (sess != null && pid > 0)
    {
        @SuppressWarnings(
            "rawtypes"
        )
        Query query = sess.createSQLQuery(
                "{CALL GetHoldingsforPF(:pid)}").addEntity(Rep_Holdings.class);
        query.setParameter("pid", pid);

        @SuppressWarnings(
            "rawtypes"
        )
        List result = query.getResultList();
        if (result != null)
        {
            if (result.size() > 0)
            {
                holdings = new ArrayList<Rep_Holdings>();
                for (int i = 0; i < result.size(); i++)
                {
                    Rep_Holdings holding = (Rep_Holdings) result.get(i);
                    holdings.add(holding);
                }
            }
        }
    }

    return holdings;
}

SQL Server中的相同过程

ALTER PROCEDURE [dbo].[GetHoldingsforPF]
    @pid int
AS
BEGIN
SET NOCOUNT ON;
        -- Insert statements for procedure here

        declare @totalPFInv decimal(15,2);

    set @totalPFInv =  ( select  sum(totalInvestment) from Holdings where pid = @pid );

    Select hid,
           pid,
           scCode,
           numUnits,
           avgPPU,
           adjPPU,
           totalInvestment,
           cast ( (totalInvestment/@totalPFInv)*100 as decimal(10,1)) as perPF,
           totalDiv,
           cast ( (totalDiv/totalInvestment)*100 as decimal(10,1)) as divY
           from Holdings
           where pid = @pid
END

相关问题