DB2-ALTER表ADD列具有唯一的默认值(UUID)

问题描述 投票:0回答:2

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

我试图通过编写如下函数来实现它:

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查询中调用自定义函数的正确格式是什么,或者为达到上述要求的任何建议。

提前感谢。

database function db2 uuid alter-table
2个回答
0
投票

您将需要通过触发器而不是作为生成的表达式来执行此操作。鉴于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

-1
投票

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

要访问现有字段值,更改表添加ID_VALUE AS(UUID_FUNC([field_name]));

© www.soinside.com 2019 - 2024. All rights reserved.