MySQL – How to Set Auto_Increment Value Based on a Variable

auto-incrementMySQL

Is it possible to set the auto-increment value in MySQL based on a variable?

SELECT 1 + MAX(id) 
INTO @newAiValue
FROM Result_Import_Archive;

ALTER TABLE Result_Import
AUTO_INCREMENT = @newAiValue;

This is what I intend to do, however, MySQL complains that it is syntactically incorrect.

Best Answer

You can do it with a prepared statement.

set @sql = concat('alter table ai auto_increment = ', @newai);
prepare stmt from @sql;
execute stmt;
deallocate prepare stmt;