SQL SERVER Cascade Delete

Source: Internet
Author: User

There are three of tables:

Company

Address

Contact

Establish foreign key in address and contact, foreign key ID is company's ID,

Then you cannot delete company arbitrarily. But if the foreign key constraints in the Cascade Delete selected, it will be associated with the address and contact with the delete.

SQL Server Cascade Delete: Automatically delete secondary table (foreign KEY constraint) content when deleting primary table

SQL Server cascade deletes an operation that contains a primary key value that is referenced by a foreign key column in an existing row of another table. In a cascade delete, the outer key value references all rows of the deleted primary key value are also removed.

Such as:

Create DATABASE Temp

Go

Use Temp

Go

CREATE TABLE UserInfo

(

UserId int identity (primary key),

UserName varchar (20),--User name

Password varchar () NOT null--password

)

CREATE TABLE Userdetails

(

ID int identity (primary key),

Name varchar () not NULL,--real name

UserId int,

FOREIGN KEY (userid) references UserInfo (userid) on DELETE cascade

)

Insert UserInfo values (' ly ', ' Jeff ')

Insert UserInfo values (' wzq ', ' wzqwzq ')

Insert UserInfo values (' LG ', ' LGLG ')

Insert Userdetails VALUES (' John Doe ', 1)

Insert Userdetails values (' Harry ', 2)

Insert Userdetails values (' Liu Liu ', 3)

At this point: delete from UserInfo Where UserId = 1 To remove the userid=1 contents of the UserInfo table and the Userdetails table

Insert UserInfo values (' ly ', ' Jeff ')

Insert UserInfo values (' wzq ', ' wzqwzq ')

Insert UserInfo values (' LG ', ' LGLG ')

Insert Userdetails VALUES (' John Doe ', 1)

Insert Userdetails values (' Harry ', 2)

Insert Userdetails values (' Liu Liu ', 3)

At this point: delete from UserInfo Where UserId = 1 Deletes the contents of the userid=1 of the UserInfo table and Userdetails table.

SQL SERVER Cascade Delete

Related Article

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.