How UPDATE and SELECT at the same time

前端 未结 3 935
無奈伤痛
無奈伤痛 2020-12-10 19:07

I need to update some rows of the tables and then display these rows. Is there a way to do this with one single query and avoid this 2 query ? :

UPDATE table         


        
相关标签:
3条回答
  • 2020-12-10 19:19

    In PostgreSQL v8.2 and newer you can do this using RETURNING:

    UPDATE table
    SET foo=1
    WHERE boo=2
    RETURNING *
    
    0 讨论(0)
  • 2020-12-10 19:39

    You can use stored procedure or function. It will contains your queries.

    0 讨论(0)
  • 2020-12-10 19:41

    You can use a stored procedure in PL/pgSQL. Take a look at the [docs][1]

    Something like this

    CREATE FUNCTION run(fooVal int, booVal int) 
    RETURNS TABLE(fooVal int, booVal int)
    AS $$
    BEGIN
      UPDATE table SET foo = fooVal WHERE boo= booVal;
      RETURN QUERY SELECT fooVal, booVal from table WHERE ( foo = fooVal ) AND ( boo = booVal );
    END;
    $$ LANGUAGE plpgsql;
    

    You will save the roundtrip time for sending another statement. This should not be a performance bottleneck. So short answer: Just use two queries. That's fine and this is how you do it in SQL.

    [1]: http://www.postgresql.org/docs/8.4/static/plpgsql.html docs

    0 讨论(0)
提交回复
热议问题