2012-09-05 64 views
2

根據HSQL documentation只有SQL過程需要CALL語法。我正在寫一個SQL函數,但我不能從它SELECT。我只能CALL它。任何人都可以看到我錯過的東西?這裏是我的代碼爲什麼我可以用SELECT調用HSQL函數,但不能調用?

public static void main(String[] args) throws Exception { 
    Class<?> driverClass = Class.forName("org.hsqldb.jdbcDriver"); 
    JDBCDriver driver = (JDBCDriver) driverClass.newInstance(); 
    Properties props = new Properties(); 
    props.setProperty("user", "sa"); 
    props.setProperty("password", ""); 
    Connection c = driver.connect("jdbc:hsqldb:mem:aname", props); 
    execute(c, "CREATE TABLE T (i INT)"); 
    execute(c, "INSERT INTO T VALUES (1)"); 
    execute(c, "CREATE FUNCTION f() RETURNS TABLE (i INT) READS SQL DATA " + 
      " RETURN TABLE (SELECT * FROM T)"); 
    System.out.println("Call returns the ResultSet:"); 
    execute(c, "{ CALL f() }"); 
    try { 
     execute(c, "SELECT * FROM f()"); 
    } catch (Exception e) { 
     System.out.println("Select throws the exception:"); 
     System.out.println(e); 
    } 
} 

private static void execute(Connection c, String sql) throws SQLException { 
    Statement s = c.createStatement(); 
    try { 
     s.execute(sql); 
     ResultSet rs = s.getResultSet(); 
     if (rs != null) { 
      printResultSet(rs); 
     } 
    } finally { 
     s.close(); 
    } 
} 

private static void printResultSet(ResultSet rs) throws SQLException { 
    try { 
     while (rs.next()) { 
      int columnCount = rs.getMetaData().getColumnCount(); 
      for (int i = 1; i <= columnCount; i++) { 
       System.out.println(rs.getObject(i)); 
      } 
     } 
    } finally { 
     rs.close(); 
    } 
} 

我得到的輸出:

Call returns the ResultSet: 
1 
Select throws the exception: 
java.sql.SQLSyntaxErrorException: user lacks privilege or object not found: F 

回答

2

選擇此函數返回表中的正確的語法如下:

SELECT * FROM TABLE(F()) 
相關問題