Return rows from a PL/pgSQL function

前端 未结 3 1550
感情败类
感情败类 2020-12-21 21:07

I have a procedure in PostgreSQL:

CREATE OR REPLACE FUNCTION get_geom_difference()
RETURNS void AS
$$
BEGIN
SELECT filedata.num,st_area(ST_Difference(ST_TRAN         


        
3条回答
  •  抹茶落季
    2020-12-21 21:17

    Although Erwin provided a great answer, I thought I'd share a version in which the function takes params, and I'm using the new postgres return query syntax within the body of the function. The difference is that it seems to set params you have to use the PreparedStatement interface rather than the higher level Statement. here's my pg function

    CREATE OR REPLACE FUNCTION gettools(_userid bigint)
      RETURNS table(id bigint,itemname character varying(250)) AS
    $BODY$
    
    begin   
        return query 
        select distinct a.id, a.itemname 
        from tool a inner join tooltie b
         on a.id = b.toolid 
         and b.userid=_userid;
    end;
    $BODY$
      LANGUAGE plpgsql STABLE
      COST 100;
    

    and here's my java that simply fills a map with data

      private static final String GET_DATASOURCES = "select * from getdatasources(?)";
    
        public Map getAuthDataSources(Long userid) {
            Map auths = new TreeMap<>();
            try {
              if (connection == null || connection.isClosed()) {
                init();
              }
              PreparedStatement cs = connection.prepareStatement(GET_DATASOURCES);
              // this is where to set the param ? for the function
              cs.setLong(1, userid);
              connection.setAutoCommit(false);        
              ResultSet result = cs.executeQuery();
    
              while (result.next()) {
                Long id = result.getLong(1);
                String itemname = result.getString(2);
                auths.put(id, itemname);
              }
              cs.close();
              connection.commit();
              connection.setAutoCommit(true);
              connection.close();
            } catch (SQLException ex) {
              LOG.error("error getting data sources", ex);
    
            }
            return auths;
          }
    

    Hope this helps someone.

提交回复
热议问题