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
- Add a new column to the existing table (Id INTEGER).
- Change the name of the existing table.
- Create a new table which includes the new primary key (Id INTEGER PRIMARY KEY).
- Insert all data from the renamed table into the newly created table.
- 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