Restart initial id of table with using MAX() method

柔情痞子 提交于 2019-12-06 16:40:13

When looking at the syntax for ALTER TABLE you will find that you can only use a constant, e.g., "RESTART WITH 12345". A query itself is not possible. For automation you would need to break it up, use a variable, generate the ALTER statement and execute it.

Assuming this is for DB2 for LUW, you can automate the process of resetting identity values with some dynamic 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

You may need to change the data type of curmax if your identities are not integer, and adjust the query against syscat.colidentattributes to use the appropriate schema name.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!