-- Create a database
Create Database test;
Go
-- Create a table MERs
Create Table customers (
Id int identity (1, 1) not null,
Name varchar (15 ),
Age int,
Primary Key (ID)
);
Go
-- Create Table orders
Create Table orders (
Id int identity (1, 1) not null,
Order_number varchar (15 ),
Price money,
Customer_id int,
Primary Key (ID)
);
Go
-- Insert data to the table orders to check the money data type. The result is: 69.0000.
Insert into orders (price) values (69 );
Select * from orders;
-- Adds Foreign keys and link constraints.
Alter table orders add constraint fk_customer foreign key (mermer_id) References MERs (ID );
Go
-- Cascade Delete and update
Alter table orders add constraint fk_customer foreign key (mermer_id) References MERs (ID)
On Delete cascade on update cascade;
Go
-- Cascading Deletion
Alter table orders add constraint fk_customer foreign key (mermer_id) References MERs (ID)
On Delete cascade;
Go
========================================================== ========================================================== ==================================
--
Insert into MERs values ('zhang san', 25 );
Insert into MERs values ('Lee 4', 25 );
-- If cascading insertion is set, the customer_id (foreign key) inserted to the sub-Table orders)
-- This ID (primary key) must exist in the customers parent table)
Insert into orders values (1, 50, 5 );
-- If cascading deletion is set, delete the records with ID = 5 in the customers parent table,
-- Records with 5 mer_id = 5 in the subtable orders will also be deleted,
Delete from MERs where id = 5