简体   繁体   中英

How UPDATE and SELECT at the same time

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 SET foo=1 WHERE boo=2

SELECT * from table WHERE ( foo=1 ) AND ( boo=2 )

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

UPDATE table
SET foo=1
WHERE boo=2
RETURNING *

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM