在DB2中动态设置Identity Start With

时间:2015-03-23 04:49:24

标签: db2

我希望能够做这样的事情来动态设置身份START WITH值。有可能吗?

CREATE VARIABLE v_number BIGINT DEFAULT 142;
ALTER TABLE txn
  ALTER COLUMN id SET DATA TYPE BIGINT NOT NULL 
     PRIMARY KEY UNIQUE 
     GENERATED BY DEFAULT AS IDENTITY (
       START WITH v_number * 1000000, INCREMENT BY 1
     );

1 个答案:

答案 0 :(得分:2)

DDL语句通常需要文字值,因此您需要使用动态SQL:

CREATE VARIABLE v_number BIGINT DEFAULT 142;
EXECUTE IMMEDIATE 'ALTER TABLE txn ' ||
  'ALTER COLUMN id SET DATA TYPE BIGINT NOT NULL' || 
     'PRIMARY KEY ' || 
     'GENERATED BY DEFAULT AS IDENTITY (' ||
       'START WITH ' || v_number || '* 1000000 INCREMENT BY 1 )';

没有理由同时声明UNIQUEPRIMARY KEY约束 - 根据定义,主键值是唯一的。