sql script function writing postgresql database implementation analysis

  • 2021-12-12 06:04:06
  • OfStack

This article mainly introduces the sql script function to write postgresql database to achieve analysis, in this article through the example code introduction is very detailed, for everyone's learning or work with a reference to learning value, the need for friends can refer to the following

postgresql creates Long self-increasing function


CREATE SEQUENCE global_id_sequence;

CREATE OR REPLACE FUNCTION seq_id(OUT result bigint) AS $$
DECLARE
  our_epoch bigint := 1314220021721;
  seq_id bigint;
  now_millis bigint;
  -- the id of this DB shard, must be set for each
  -- schema shard you have - you could pass this as a parameter too
  shard_id int := 1;
BEGIN
  SELECT nextval('global_id_sequence') % 1024 INTO seq_id;

  SELECT FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000) INTO now_millis;
  result := (now_millis - our_epoch) << 23;
  result := result | (shard_id << 10);
  result := result | (seq_id);
END;
$$ LANGUAGE PLPGSQL;

<!--alter function seq_id(out bigint) owner to postgres;-->

Create sql script postgresql


do language plpgsql
$$
begin
update grade set grade = 90 where sno = '20161003';
end
$$

Related articles: