30 June 2016

Sql Server create table, alter table add constraint primary key and foreign key Join view


--[1]
USE MASTER;
GO
IF EXISTS (SELECT * FROM sys.databases WHERE name = 'AZBank_Demo')
DROP DATABASE AZBank_Demo
GO
CREATE DATABASE AZBank_Demo;
GO
USE AZBank_Demo;
GO
--[2]
CREATE TABLE Customer
(
CustomerId int Not null,
Name nvarchar(50),
City nvarchar(50),
Country nvarchar(50),
Phone nvarchar(15),
Email nvarchar(50)
);
GO
CREATE TABLE CustomerAccount
(
AccountNumber char(9) Not null,
CustomerId int Not null,
Balance money Not null,
MinAccount money
);
GO
CREATE TABLE CustomerTransaction
(
transactionId int Not null,
AccountNumber char(9),
TransactionDate smalldatetime,
Amount money,
DepositorWithdraw bit
);
GO
ALTER TABLE Customer ADD CONSTRAINT PK_Customer PRIMARY KEY (CustomerId);
GO
ALTER TABLE CustomerAccount ADD CONSTRAINT FK_CustomerAccount FOREIGN KEY (CustomerId) REFERENCES Customer (CustomerId);
GO
ALTER TABLE CustomerAccount ADD CONSTRAINT PK_CustomerAccount PRIMARY KEY (AccountNumber);
GO
ALTER TABLE CustomerTransaction ADD CONSTRAINT FK_CustomerTransaction FOREIGN KEY (AccountNumber) REFERENCES CustomerAccount (AccountNumber);
GO
ALTER TABLE CustomerTransaction ADD CONSTRAINT PK_CustomerTransaction PRIMARY KEY (transactionId);
--[3] 
INSERT INTO Customer
VALUES
(123,N'Hải',N'Nam Định',N'Việt Nam','0983234234','ADBank@gmail.com'),
(124,N'Thu',N'Hà Nội',N'Việt Nam','0983234235','HaBank@gmail.com'),
(125,N'Minh',N'Lạng Sơn',N'Việt Nam','0983234236','MinBank@gmail.com');
GO
INSERT INTO CustomerAccount
VALUES
(001,123,8000,90),
(002,123,900,40),
(003,123,1000,20);
GO
INSERT INTO CustomerTransaction
VALUES
(223,001,'2015/4/1',90000,1),
(224,002,'2005/3/1',8000,1),
(225,003,'2005/3/2',100,0);
GO
--[4]
SELECT * FROM Customer WHERE City=N'Hà Nội';
GO
--[5]
SELECT Name 'Tên',Phone 'Điện thoại',Email,AccountNumber 'Số tài khoản',Balance 'Số dư'
FROM customer JOIN customeraccount ON customer.customerid = customeraccount.customerid
GO
--[6]
ALTER TABLE CustomerTransaction ADD CONSTRAINT CK_Amount CHECK (Amount > 0 AND Amount < 1000000);
GO
--[7]
CREATE INDEX
GO
--[8]
CREATE VIEW vCustomerTransactions AS
SELECT Name 'Tên',CT.AccountNumber 'Tài khoản', TransactionDate 'Ngày', Amount,DepositorWithdraw FROM Customer C, CustomerAccount CA, CustomerTransaction CT 
WHERE C.CustomerId=CA.CustomerId AND CA.AccountNumber=CT.AccountNumber;
GO
--[9] 
CREATE PROCEDURE => http://giai-ma.blogspot.com/2016/06/stored-procedure.html

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang