I want to add a column of type TEXT
, NOT NULL
, with a DEFAULT
value of empty string, which should reference a column in a different table. I can add foreign key references when creating a table.
But it's not allowing me to add a column with a foreign key reference:
ALTER TABLE Event ADD TagId TEXT NOT NULL DEFAULT '';
ALTER TABLE Event
ADD CONSTRAINT FK_TagId FOREIGN KEY ("TagId") REFERENCES "Tag" ("TagId") ON DELETE RESTRICT;
I want to add a column of type TEXT
, NOT NULL
, with a DEFAULT
value of empty string, which should reference a column in a different table. I can add foreign key references when creating a table.
But it's not allowing me to add a column with a foreign key reference:
ALTER TABLE Event ADD TagId TEXT NOT NULL DEFAULT '';
ALTER TABLE Event
ADD CONSTRAINT FK_TagId FOREIGN KEY ("TagId") REFERENCES "Tag" ("TagId") ON DELETE RESTRICT;
Share
Improve this question
edited Feb 1 at 4:15
user4157124
2,99614 gold badges31 silver badges46 bronze badges
asked Jan 31 at 10:03
MartinMartin
217 bronze badges
2
|
1 Answer
Reset to default 0Following the comments from @user4157124 I have removed my original answer and offer the following script, which I hope is closer to the actual details referred to in the question:
DROP TABLE IF EXISTS Event;
DROP TABLE IF EXISTS Tag;
CREATE TABLE Event (Name TEXT, Id INTEGER PRIMARY KEY AUTOINCREMENT);
INSERT INTO Event(Name) VALUES("EventA");
INSERT INTO Event(Name) VALUES("EventB");
CREATE TABLE Tag (Name TEXT, TagId TEXT);
INSERT INTO Tag VALUES ("TagA", "TagA");
INSERT INTO Tag VALUES ("TagB", "TagB");
SELECT * FROM Event;
ALTER TABLE Event ADD COLUMN TagId TEXT NOT NULL DEFAULT '' REFERENCES Tag(TagId);
UPDATE Event Set TagId = "TagA" WHERE Name = "EventA";
UPDATE Event Set TagId = "TagB" WHERE Name = "EventB";
SELECT * FROM Event;
The script can be run from the SQLite command prompt via the following commands:
sqlite3 test.db
.headers on
.mode columns
.read script.sql
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745270202a4619698.html
ALTER TABLE
syntax, there's this to consider: If foreign key constraints are enabled and a column with a REFERENCES clause is added, the column must have a default value of NULL – Shawn Commented Jan 31 at 13:41