使用 MAX() 方法重新启动 table 的初始 ID

Restart initial id of table with using MAX() method

我正在对 table 进行一些更改,但我无法找出问题所在。 这是我的 SQL 脚本;

ALTER TABLE X ALTER COLUMN X_ID RESTART WITH (SELECT MAX(X_ID) FROM X);

尽管我使用 AS 而不是 WITH 并尝试了其他组合,但我找不到确切的语法。 (顺便说一句,我不能在初始化中设置这个 属性,我必须在创建 table 之后设置它)

查看 ALTER TABLE 的语法时,您会发现只能使用常量,例如 "RESTART WITH 12345"。查询本身是不可能的。对于自动化,您需要将其分解,使用变量,生成 ALTER 语句并执行它。

假设这是针对 LUW 的 DB2,您可以使用一些动态 SQL:

自动执行重置身份值的过程
begin
 declare curmax bigint;
 for r as select tabschema, tabname, colname, nextcachefirstvalue, seqid 
          from syscat.colidentattributes where tabschema = current_schema
  do
   prepare s from 
    'select max(' || r.colname || ') from ' || 
     rtrim(r.tabschema) || '.' || r.tabname;
   begin
    declare c cursor for s;
    open c;
    fetch c into curmax;
    close c;
   end;
   if curmax >= r.nextcachefirstvalue
   then
    execute immediate 
     'alter table ' || rtrim(r.tabschema) || '.' || r.tabname ||
     ' alter column ' || r.colname || ' restart with ' || varchar(curmax+1);
   end if;
  end for;
end

如果您的身份不是整数,您可能需要更改 curmax 的数据类型,并调整针对 syscat.colidentattributes 的查询以使用适当的架构名称。