如何在 Firebird 的 table 上创建默认约束以分配自动生成的 UUID 值

How to create default constraint on the table of Firebird to assign auto-generated UUID value

我正在尝试使用 UUID (CHAR(16) CHARACTER SET OCTETS) 列类型定义 table。看完Firebird 3.0 Developer's Guide,发现只支持context-variables/simple expression/constant。我想知道是否有办法在 table 上定义默认约束以调用 GEN_UUID() 分配 UUID 进行插入?

您不能使用 DEFAULT 子句来执行此操作,因为它只允许文字和 Firebird 文档所指的 select 数字 'context variables'.

为了做你想做的事,你需要创建一个 before insert trigger 来生成值。像这样:

create trigger bi_yourtable before insert on yourtable
as
begin
  new.uuid_column = gen_uuid();
end

或者,如果您不想无条件生成 UUID:

create trigger bi_yourtable before insert on yourtable
as
begin
  if (new.uuid_column is null) then
  begin
    new.uuid_column = gen_uuid();
  end
end