Server
There are 3 ways to establish foreign key constraints in SQL Server:
1.Enterprise Manager, Tables,design table, set the properties of the table,
can establish constraint, reference key;
2.Enterprise Manager, diagrams, new diagrams, establishes a two-table relationship.
3. Direct use of Transact SQL statements.
Three methods need to establish a data table first.
--Create TABLE Author:
CREATE TABLE [dbo]. [Author] (
[ID] [bigint] not NULL,
[AuthorName] [Char] (a) NULL,
[Address] [Char] () NULL,
[Introduction] [ntext] Null
)
To set the Authorid in table Mybbs as a foreign key, use the Transact SQL statement directly, referring to the ID field of the author table, as follows:
--Adds a foreign key constraint to the table Mybbs (Authorid) Fk_mybbs_author, and Authorid in table Mybbs is constrained by the primary key ID in the 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 the 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.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.