Recursive CTE don't work when recursion predicate uses a bind variable

血红的双手。 提交于 2019-12-13 08:51:04

问题


When using recursive CTE in H2 (I know, experimental feature), the following query doesn't work:

Connection con = getConnection();
System.out.println("Wrong result:");
PreparedStatement stmt = con.prepareStatement(
    "WITH recursive t(f) AS ( "+
    "    SELECT 1             "+
    "    UNION ALL            "+
    "    SELECT t.f + 1       "+
    "    FROM t               "+
    "    WHERE t.f < ?        "+
    ")                        "+
    "SELECT t.f               "+
    "FROM t                   "
);
stmt.setInt(1, 10);
ResultSet rs = stmt.executeQuery();

while (rs.next())
    System.out.println(rs.getInt(1));

The produced output is:

1

The expected result would be:

1
2
3
4
5
6
7
8
9
10

What's the problem?


回答1:


This is a known issue (see here). H2 has problems when recursive queries contain bind variables. The following query doesn't use bind values and works as expected:

System.out.println("Correct result:");
rs = con.createStatement().executeQuery(
    "WITH recursive t(f) AS ( "+
    "    SELECT 1             "+
    "    UNION ALL            "+
    "    SELECT t.f + 1       "+
    "    FROM t               "+
    "    WHERE t.f < 10       "+
    ")                        "+
    "SELECT t.f               "+
    "FROM t                   "
);

while (rs.next())
    System.out.println(rs.getInt(1));


来源:https://stackoverflow.com/questions/32827660/recursive-cte-dont-work-when-recursion-predicate-uses-a-bind-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!