开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜