开发者

Postgresql - how can i create a version column with integer value?

how can i create in a table a column with an integer value (starting by 0 when i insert a row开发者_如何转开发) that will be incremented by 1 every time i update a row ?

I need it to use it as optimistic locking.

Thanks.


You will need to use a trigger to achieve this. There is no automatic or built-in solution for this

create table some_table
(
   id serial primary key, 
   some_data text, 
   version integer not null default 0
);

create or replace function increment_version()
  returns trigger
as
$body$
begin
  new.version := new.version + 1;
  return new;
end;
$body$
language plpgsql;

create trigger version_trigger
   before update on some_table
   for each row execute procedure increment_version();

Note that the trigger function can be used for any table that contains a column named version (that is a number).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜