SQL cascade deletion of databases

Source: Internet
Author: User

Function: automatically deletes the content of a sub-table (foreign key constraint) When deleting a primary table.

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:

 
 
  1. Create database temp
  2. Go
  3. Use temp
  4. Go
  5.  
  6. Create table UserInfo
  7. (
  8. UserId int identity (1, 1) primary key,
  9. UserName varchar (20), -- User Name
  10. Password varchar (20) not null -- password
  11. )
  12.  
  13. Create table UserDetails
  14. (
  15. Id int identity (1, 1) primary key,
  16. Name varchar (50) not null, -- real name
  17. UserId int,
  18. Foreign key (userId) references UserInfo (UserId) on delete cascade
  19. )
  20.  
  21. Insert UserInfo values ('ly ', 'jeff ')
  22. Insert UserInfo values ('wzq', 'wzqwzq ')
  23. Insert UserInfo values ('lg ', 'lglg ')
  24. Insert UserDetails values ('Li si', 1)
  25. Insert UserDetails values ('wang wu', 2)
  26. Insert UserDetails values ('Liu liu', 3)

SQL Server supports cascade update and deletion.

Oracle only supports cascading Deletion

 
 
  1. Alter table name
  2. Add constraint foreign key name
  3. Foreign key (field name) references main table name (field name)
  4. On delete cascade

Syntax:

 
 
  1. Foreign Key 
  2. (column[,...n]) 
  3. references referenced_table_name[(ref_column[,...n])] 
  4. [on delete cascade] 
  5. [on update cascade] 

Note:

  • Column: column name
  • Referenced_table_name: name of the primary key table referenced by the foreign key
  • Ref_name: primary key column of the Table to be referenced by the foreign key
  • On delete: deletes a cascading.
  • On update: update Cascade

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.