问题
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