SQL Server QL Statement Delete foreign key and delete
alter table tablename add constraint ordersrelationship
foreign key Mployeeid
references employees (EmployeeID)
on delete cascade
on update cascade
ALTER TABLE books add constrait name--Specify a name
Add foreign Key (ISBN) references readers (readerid);
ALTER TABLE books DROP constraint foreign health name
Set the method and step of Authorid for SQL foreign key in table Mybbs, hope to be able to enlighten you.
Set the Authorid in table Mybbs as a foreign key to SQL Server, referencing the ID field of the author table, using the Transact SQL statement directly, as follows:
--Adds a SQL Server FOREIGN KEY constraint fk_mybbs_author for table Mybbs (Authorid), and Authorid in table Mybbs is constrained by the SQL Server primary key ID in table author:
BEGIN TRANSACTION
ALTER TABLE DBO.MYBBS add constraint Fk_mybbs_author
Foreign KEY (Authorid)
References Dbo.author ([ID]) on UPDATE cascade on DELETE CASCADE
--Delete SL foreign KEY constraint Fk_mybbs_author:
--alter table Dbo.mybbs drop constraint Fk_mybbs_author
--rollback
Commit TRANSACTION
The above on update cascade,on delete Cascade Two options, indicating that the ID field of the author table after delete,update operation, the IDs in the Mybbs table are also deleted or updated. If unchecked, it is not possible to update or delete an ID that has been associated with the Mybbs table in the author table.
Look at an example
CREATE TABLE ' board ' (
' board_id ' int (one) not NULL auto_increment,
' catalog_id ' int (one) not null default ' 0 ',
' board_name ' varchar character set UTF8 NOT null default ',
' Board_descrip ' varchar (255) Character Set UTF8 default null,
' Board_type ' varchar character set UTF8 default null,
Primary KEY (' board_id '),
Key ' foreign key ' (' catalog_id '),
Constraint ' foreign KEY constraint ' foreign key (' catalog_id ') references ' catalog ' (' catalog_id ') on DELETE cascade on UPDATE CASCADE//CASCADE Delete The key statement
) Engine=innodb auto_increment=13 default CHARSET=GBK;
SQL foreign key for two purposes:
1/, the most commonly used one: reduce duplication of data. Table A has a foreign key, and table B's data is basically not allowed to be deleted. Then select the enforce relationship for insert and update.
2/, Second, is to add a subordinate table. If Table A deletes a record, table B also deletes an associated record in the foreign key relationship, and the primary key of table A is the foreign key of table B. This relationship, in fact table B is the subordinate table of table A (that is, table A is the parent table), when you select the force relation to insert and update, if you insert data into table B, there must already be a corresponding record in table A. When you select a cascade to delete related fields, deleting one of the records in table a deletes a record in the corresponding table B.
*/
?>