Restart initial id of table with using MAX() method

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 )

Upvotes: 4

Views: 4973

Answers (2)

mustaccio
mustaccio

Reputation: 19004

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.

Upvotes: 2

data_henrik
data_henrik

Reputation: 17156

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.

Upvotes: 5

Related Questions