views:

26

answers:

1

I have just managed to migrate a pretty big database from SQL Server to MySQL. I didn't set the primary keys to auto increment during the migration because the tables have relationships based on ids as primary keys which are foreign keys in another table.

Now for adding new records I want to alter the primary key 'id' columns in all tables to be autoincrement but starting from the last highest number in the id column in each table.

What's the best way to do this without losing the relationships I already have?

UPDATE: Trying to add autoincrement gives me this error:

ERROR 1067: Invalid default value for 'id'

SQL Statement:

ALTER TABLE `skandium`.`brands` CHANGE COLUMN `id` `id` INT(11) NOT NULL DEFAULT '0' AUTO_INCREMENT

ERROR 1050: Table 'brands' already exists

SQL Statement:

CREATE TABLE `brands` (
  `id` int(11) NOT NULL DEFAULT '0',
  `brand` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
+1  A: 

Just add the auto-increment on your needed columns. It won't affect existing rows. It will start with the next available value.

Note that a column being auto-increment means just that if you don't assign a value to it one will be added by MySQL. If you want to supply explicit values you can do so without anything special happening. So you could have set those columns to auto-increment right from the start.

A column with auto-increment cannot have an explicit default value.

Tested

Alin Purcaru
@Alin: I get an error when I try to do that. See update in Question
Moin Zaman
@Moin I don't think you should have a default for autoincrements. It doesn't make sense. I'll test it now and let you know.
Alin Purcaru
The default value *is* the one specified by the autoincrement property. So you can't set it explicitly.
Alin Purcaru