pgsql使用触发器在新增数据时生成uuid作为主键

1.创建uuid生成函数

CREATE OR REPLACE FUNCTION "public"."uuid"()
  RETURNS "pg_catalog"."text" AS $BODY$
DECLARE passed BOOLEAN ;
BEGIN
	RETURN (
		SELECT
			REPLACE (
				uuid_in (
					md5(
					random() :: TEXT || now() :: TEXT
					) :: cstring
				) :: TEXT,
				'-' :: TEXT,
				'' :: TEXT
			)
	) ; RETURN passed ;
END ; $BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100

  2.创建触发器函数

CREATE OR REPLACE FUNCTION "public"."create_uuid"()
  RETURNS "pg_catalog"."trigger" AS $BODY$
BEGIN
    NEW.ID := uuid();
    RETURN NEW;
END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100

  3.创建触发器

CREATE TRIGGER "[触发器名]" BEFORE INSERT ON "public"."[表名]"
FOR EACH ROW
WHEN ((new.id IS NULL))
EXECUTE PROCEDURE "public"."create_uuid"();

  

转载于:https://www.cnblogs.com/gremlin/p/9523299.html

你可能感兴趣的:(pgsql使用触发器在新增数据时生成uuid作为主键)