[SQL Server] [basic] multi-Table Association Creation

Source: Internet
Author: User

If object_id ('tablecd') is not null drop table tablecd --- add an intermediate table for multiple to multiple pairs
Go
If object_id ('tabled ') is not null drop table tabled
Go
If object_id ('tablec') is not null drop table tablec
Go
If object_id ('tableb') is not null drop table tableb
Go
If object_id ('tablea') is not null drop table tablea
Go
Create Table tablea (Aid varchar (10) primary key, aname varchar (20 ))
Insert tablea select 'a1', 'Company 1'
Go
Create Table tableb (BID varchar (10) primary key, bname varchar (20), Aid varchar (10) References tablea (AID ))
Insert tableb
Select 'b1 ', 'department 1', 'a1' Union all
Select 'b2', 'department 2', 'a1'
Go
Create Table tablec (CID varchar (10) primary key, cname varchar (20), bid varchar (10) References tableb (BID ))
Insert tablec
Select 'c1 ', 'personnel 1', 'b1' Union all
Select 'c2 ', 'staff 2', 'b1' Union all
Select 'c3', 'personnel 3', 'b2' Union all
Select 'c4 ', 'personnel 4', 'b2'
Go
Create Table tabled (did varchar (10) primary key, dname varchar (20 ))
Insert tabled
Select 'd1 ', 'permission 1' Union all
Select 'd2 ', 'permission 2' Union all
Select 'd3 ', 'permission 3' Union all
Select 'd4 ', 'permission 4'
Go
Create Table tablecd (cdid int identity primary key, CID varchar (10) References tablec (CID) on Delete cascade, did varchar (10) References tabled (did) on Delete cascade)
Insert tablecd
Select 'c1 ', 'd1' Union all
Select 'c1 ', 'd2' Union all
Select 'c2 ', 'd1' Union all
Select 'c3', 'd4'

Delete tablec where cid = 'c1'
-- Or
-- Delete tabled Where did = '1'

Select * From tablecd

/*

(One row is affected)

(2 rows affected)

(Four rows affected)

(Four rows affected)

(Four rows affected)

(One row is affected)
Cdid Cid did
-------------------------------
3 C2 d1
4 C3 D4

(2 rows affected)

*/

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.