Simple implementation of SQL Server cascading Deletion

Source: Internet
Author: User

SQL Server cascading deletion: When you delete a primary table, the content of the secondary table (foreign key constraint) is automatically deleted.

The SQL Server cascade operation to delete a row that contains the primary key value. This value is referenced by a foreign key column in an existing row of another table. In cascading deletion, all rows whose foreign key value references the deleted primary key value are also deleted.

For example:

Create Database temp
Go
Use temp
Go

Create Table userinfo
(
Userid int identity (1, 1) primary key,
Username varchar (20), -- User Name
Password varchar (20) not null -- Password
)

Create Table userdetails
(
Id int identity (1, 1) primary key,
Name varchar (50) 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 ('Li si', 1)
Insert userdetails values ('wang wu', 2)
Insert userdetails values ('Liu liu', 3)

Delete from userinfo where userid = 1 to delete the userid = 1 in the userinfo and userdetails tables.

Insert userinfo values ('ly ', 'jeff ')
Insert userinfo values ('wzq', 'wzqwzq ')
Insert userinfo values ('lg ', 'lglg ')

Insert userdetails values ('Li si', 1)
Insert userdetails values ('wang wu', 2)
Insert userdetails values ('Liu liu', 3)

Delete from userinfo where userid = 1 to delete the userid = 1 in the userinfo and userdetails tables.

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.