当递归谓词使用绑定变量时,递归 CTE 不起作用
Recursive CTE don't work when recursion predicate uses a bind variable
在 H2 中使用递归 CTE 时(我知道,实验性功能),以下查询不起作用:
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));
产生的输出是:
1
预期结果为:
1
2
3
4
5
6
7
8
9
10
有什么问题?
这是一个已知问题 (see here)。当递归查询包含绑定变量时,H2 会出现问题。以下查询不使用绑定值并按预期工作:
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));
在 H2 中使用递归 CTE 时(我知道,实验性功能),以下查询不起作用:
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));
产生的输出是:
1
预期结果为:
1
2
3
4
5
6
7
8
9
10
有什么问题?
这是一个已知问题 (see here)。当递归查询包含绑定变量时,H2 会出现问题。以下查询不使用绑定值并按预期工作:
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));