Data | database-building a database
Create DATABASE test;
Go
--Establish table customers
CREATE TABLE Customers (
ID int identity (1,1) not NULL,
Name varchar (15),
Age int,
Primary KEY (ID)
);
Go
--Establish the table orders
CREATE TABLE Orders (
ID int identity (1,1) not NULL,
Order_number varchar (15),
Price,
customer_id int,
Primary KEY (ID)
);
Go
--Inserts data into the table orders to detect the Money data type, and the result is: 69.0000
INSERT into orders (price) values (69);
SELECT * from Orders;
--adding foreign keys and relationship constraints
ALTER TABLE orders add constraint Fk_customer foreign key (customer_id) references customers (ID);
Go
-Cascade Delete, update
ALTER TABLE orders add constraint Fk_customer foreign key (customer_id) references customers (ID)
On the DELETE cascade on UPDATE cascade;
Go
--Cascading deletion
ALTER TABLE orders add constraint Fk_customer foreign key (customer_id) references customers (ID)
ON DELETE cascade;
Go
=====================================================================================================
--
INSERT into customers values (' John ', 25);
INSERT into customers values (' Dick ', 25);
--If a cascade insert is set, the customer_id (foreign key) inserted into the child table orders
--This ID must be present in the parent table customers (primary key)
INSERT into orders values (1,50,5);
--If a cascade deletion is set, the id=5 record in the parent table customers is deleted.
--also deletes customer_id=5 records in the child table orders,
Delete from customers where id=5
--Query
SELECT * from Customers;
SELECT * from Orders;
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.