DB2 - ALTER table 添加具有唯一默认值 (UUID) 的列

DB2 - ALTER table ADD column with unique default value (UUID)

我需要通过添加默认值为 UUID 和数据类型为 VARCHAR(255) 的新列来更新现有 table。

我试图通过编写一个函数来实现它:

CREATE FUNCTION UUID_FUNC()
     RETURNS VARCHAR(255)
     LANGUAGE SQL 
     BEGIN ATOMIC
     DECLARE UUID VARCHAR(4000);
     SET UUID = (SELECT TRIM(CHAR(HEX(GENERATE_UNIQUE()))) from sysibm.sysdummy1);
     RETURN UUID;
END

并在查询中将其用作:

ALTER TABLE <Table-name> 
    ADD ID_VALUE VARCHAR(255) NOT NULL DEFAULT (UUID_FUNC())

执行上述查询时出现以下错误:

SQL Error [42601]: An unexpected token "DEFAULT" was found following "ARCHAR(255) NOT NULL".  
Expected tokens may include:  "CHECK".. SQLCODE=-104, SQLSTATE=42601, DRIVER=3.59.81

在 ALTER 查询中调用自定义函数的正确格式是什么,或者任何实现上述要求的建议。

提前致谢。

更改TABLE 添加ID_VALUE AS (UUID_FUNC());

为了访问现有的字段值, 更改 TABLE 添加 ID_VALUE AS (UUID_FUNC([field_name]));

您需要通过触发器而不是生成的表达式来执行此操作。鉴于 DDL:

create or replace function your.uuid_func()
   returns char(26)
   language sql
   not deterministic
   return values(hex(generate_unique()));

create table your.table (
   c1 int not null,
   c2 char(26) not null
);

您可以创建触发器:

create trigger set_uuid
   before insert on your.table
   referencing new as n
   for each row
   when (n.id_value is null)
      set n.id_value = your.uuid_func();

然后插入:

—- You can insert a normal string:
insert into your.table (c1, c2)
   values (1, ‘anything’);


—- Or, if you don’t provide a value for c2, it will be set
—- to the value of UUID_FUNC():

insert into your.table (c1) 
    values (2);

结果:

select * from your.table;

C1          C2                        
----------- --------------------------
          1 anything                     
          2 20200111154913255440000000

我是通过以下方式实现的:

ALTER TABLE <Table-name> ADD ID_VALUE VARCHAR(255) NOT NULL DEFAULT '0';

UPDATE <Table-name> SET ID_VALUE=(hex(GENERATE_UNIQUE())) WHERE ID_VALUE='0';