Restart initial id of table with using MAX() method

女生的网名这么多〃 提交于 2019-12-08 08:37:08

问题


I am doing some changes on my table and I couldn't figure out the problem. This is my SQL script;

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

Altough I used AS instead of WITH and tried other combinations, I couldn't find the exact syntax. (By the way, I cannot set this property in the initialization, I got to do it after creation of the table )


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/32965457/restart-initial-id-of-table-with-using-max-method

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