lundi 2 février 2015

SQLite: Add column with primary key to existing table whilst persisting data

Within the context of SQLite.


I have an existing table which is currently populated with numerous rows of data.


I am trying to add a new primary key column to this table whilst persisting the original data.


As demonstrated below, I have tried the following



  1. Add a new column to the existing table (Id INTEGER).

  2. Change the name of the existing table.

  3. Create a new table which includes the new primary key (Id INTEGER PRIMARY KEY).

  4. Insert all data from the renamed table into the newly created table.

  5. Drop the renamed table.


The reason I thought this would work is because according to SQlite documentation,



A column declared INTEGER PRIMARY KEY will autoincrement.



However I am receiving the following error.



ErrorCode : 19
Message : constraint failed
UNIQUE constraint failed: Person.Id
Result : Constraint


Here is my code.



--Add a new column to the existing table(Id INT).
ALTER TABLE [Person]
ADD Id INTEGER;

--Change the name of the existing table.
ALTER TABLE [Person] RENAME TO Person_temp;

--Create a new table which includes the new PK.
CREATE TABLE Person(
Id INTEGER PRIMARY KEY,
FirstName nvarchar(100) NULL,
LastName nvarchar(100) NULL
);

--Insert all data from the renamed table into the new table.
INSERT INTO Person SELECT * FROM Person_temp;

--Drop the renamed table.
DROP TABLE Person_temp;


Could anyone be kind enough to shed some light?


Aucun commentaire:

Enregistrer un commentaire