How to deal with foreign key constraints when changing the data type of a column?

First, we first create the table and establish constraints

【表COURSE】

CREATE TABLE Course(
					Cno CHAR(4)PRIMARY KEY,
					Cname CHAR(40) NOT NULL,
					Cpno CHAR(4),
					Ccredit SMALLINT,
					FOREIGN KEY (Cpno) REFERENCES COURSE(Cno)
					);

The table COURSE here refers to the Cno attribute of the table Course (ie itself) .
We try to modify the data type of the attribute Cno of the table Course ;

ALTER TABLE course MODIFY Cno char(6);

Run will display error.
Insert picture description here
Because this column has a foreign key constraint, it cannot be changed.
Then if we still want to change, we can delete the foreign key constraint first, and then add the constraint after the modification.

alter table Course drop foreign key course_ibfk_1;

The course_ibfk_1 here is the foreign key constraint name given by the error message.
Then we run the type change statement again.

Insert picture description here

Show success, and then we can add foreign key constraints as needed.
At this time, the data type of the foreign key is still the type when it was created, and can be modified as needed before adding the foreign key

ALTER TABLE SC ADD FOREIGN KEY (Cno) REFERENCES Course(Cno);

Insert picture description here
If there are any errors, please correct me.
Creation is not easy, one-click three consecutive.
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_42392049/article/details/113251470