You are on page 1of 16

--tạo database QLNV

create database QLNV;


--sử dụng QLNV
use QLNV;

--tạo table Phong


Create table Phong(
MAPHONG char(3),
TENPHONG nvarchar(40),
constraint pk_MP primary key(MAPHONG)
)
--tạo table NHANVIEN
Create table Nhanvien(
MANV char(3),
HOTEN nvarchar(50),
NGAYSINH date,
MAPHONG char(3),
constraint pk_manv primary key(MANV),
constraint fk_mp foreign key(MAPHONG) references Phong(MAPHONG)
)

--Thêm dữ liệu cho bảng Phong


Insert into Phong values ('P01','IT')
Insert into Phong values ('P02',N'Nhân Sự')
Insert into Phong values ('P03',N'Kế Toán')

select * from Phong

--Thêm dữ liệu cho bảng Nhân Viên


Insert into Nhanvien values('N01',N'Nguyễn Văn Hưng','01/2/2000','P01')
Insert into Nhanvien values('N02',N'Nguyễn Văn Việt ','05/10/1999','P01')
Insert into Nhanvien values('N03',N'Lê Thị Thúy ','11/08/2000','P03')
Insert into Nhanvien values('N04',N'Nguyễn Trần Huy ','18/08/2001','P02')
Insert into Nhanvien values('N05',N'Nguyễn Thị Hoài Thương ','12/11/2000','P01')
--Chạy thủ tục
Create PROC SP_DSPHONGBAN
@MAPHONG char(3)
AS
Select MANV,HOTEN,NGAYSINH
FROM Nhanvien
Where MAPHONG = @MAPHONG;

--Biên Dịch
EXEC SP_DSPHONGBAN'P03'
-- Vd2 Hiển thị thông tin tổng số nhân viên trong phòng khi người dùng nhập mã phòng
Create PROC SP_TOTALNV
@MAPHONG char(3)
AS
Select COUNT(*)
from Nhanvien
where MAPHONG=@MAPHONG

EXEC SP_TOTALNV'P01'

---- Vd2 Hiển thị thông tin tổng số nhân viên trong phòng khi người dùng nhập mã phòng
Create PROC SP_TOTAL3
@MAPHONG char(3),
@SOLUONG int output
AS
Select @SOLUONG=COUNT(*)
from Nhanvien
where MAPHONG=@MAPHONG;
--Thủ tục với tham số mặc định
Create proc SP_TOTAL4
@MAPHONG char(3) = 'P01',
@Soluong int output
As
Select @Soluong = COUNT(*)
from Nhanvien
where MAPHONG = @MAPHONG
Go
Declare @Dem int;
exec SP_TOTAL4 @Soluong=@Dem output
print 'SO LUONG NHAN VIEN PHONG' + ' ' + 'la: '+cast(@Dem as char(20));
--Thực hiện thủ tục
Declare @DEM int;
Declare @Phong char(3);
Set @Phong = 'P04'
Exec SP_TOTAL3 @MAPHONG= @Phong,@SOLUONG = @DEM OUTPUT
if @Phong != 'P04'
Print 'SO LUONG NHAN VIEN PHONG'+' '+@PHONG+' ' +'LA:'+CAST(@DEM AS
char(20));
else
print 'KHONG CO PHONG NAO CO MA LA' + ' ' +@Phong+' ';

--Viết thủ tục khi người dùng nhập vào mã nhân viên thì hiển thị thông tin của nhân viên
--và phòng ban tương ứng
Drop PROC SP_INFONV
Create PROC SP_INFONV
@MANV char(3)
AS
begin
Select NV.MANV,NV.HOTEN,NV.NGAYSINH,P.MAPHONG,P.TENPHONG from
Nhanvien NV Inner join Phong P On NV.MAPHONG = P.MAPHONG
where MANV = @MANV;
End
Exec SP_INFONV'N03'
--Viết thủ tục khi người dùng nhập vào Tên nhân viên thì hiển thị thông tin của nhân viên
-- và phòng ban tương ứng
CREATE PROC SP_INFOBYTENNV
@TEN NVARCHAR(50)
AS
SELECT N.*, P.TENPHONG
FROM NHANVIEN N, PHONG P
WHERE N.HOTEN LIKE '%' + @TEN AND N.MAPHONG = P.MAPHONG;
Go

Exec SP_INFOBYTENNV N'Thương '

--c2
Create Proc SP_NVFromTen
@Ten nvarchar(50)
As
Select nv.*, p.TenPhong
From NhanVien nv, Phong p
Where (LTRIM(RIGHT (HoTen, CHARINDEX(' ', REVERSE(HoTen)))) = @Ten)
and (nv.MaPhong = p.MaPhong);
Exec SP_NVFromTen N'Thương '

--Viết thủ tục nhập vào họ nhân viên,thì hiển thị thông tin của nhân viên
-- và phòng ban tương ứng
Create PROC SP_INFOHONV2
@HOTEN nvarchar(40)
AS
Select nv.*,p.TENPHONG
from Nhanvien nv, Phong p
where HOTEN like @HOTEN + '%' and nv.MAPHONG = p.MAPHONG;
go
--Biên dịch
Exec SP_INFOHONV2 N'Nguyễn'

select * from Nhanvien


--Viết thủ tục nhập dữ liệu cho bảng PHONG, nếu trùng khóa thì phải báo lỗi ngược lại
--ra thông báo nhập dữ liệu thành công
ALTER PROC SP_ADDPHONG
@MAPHONG char(3),
@TENPHONG nvarchar(40)
As
Begin
if Exists(Select * from Phong where MAPHONG = @MAPHONG)
begin
print N'MAPHONG đã tồn tại. Vui lòng nhập mã khác';
return -1;
end
else
begin
insert into Phong
values (@MAPHONG,@TENPHONG)
print N'Thêm thành công';
end
end

--Biên Dịch SP_ADDPhong


Exec SP_ADDPHONG 'P04',N'Bảo Trì';

Select * from Phong


--Viết thủ tục nhập dữ liệu cho bảng NHANVIEN, nếu trùng khóa thì phải báo lỗi ngược lại
--ra thông báo nhập dữ liệu thành công.Kiểm tra không tồn tại PHONG thì cũng ra câu thông
báo.Giao diện nhập dữ liệu
Alter PROC SP_ADDNV
@MANV char(3),
@HOTEN nvarchar(40),
@NGAYSINH date,
@MAPHONG char(3)
As
begin
if not exists(Select * from Phong where MAPHONG = @MAPHONG)
print N'Không tồn tại mã phòng' + ' ' +@MAPHONG ;
else
if exists(select * from Nhanvien where MANV = @MANV)
print N'MANV '+' '+ @MANV+' '+N'đã tồn tại. Vui lòng nhập MANV khác';
else
begin
insert into Nhanvien
values(@MANV,@HOTEN,@NGAYSINH,@MAPHONG)
print N'Thêm nhân viên'+' ' + @MANV +' '+ 'thành công';
end
end
--Biên dịch
Exec SP_ADDNV 'N06',N'Nguyễn Thị Mai','07/05/2000','P03'
select * from Phong
select * from Nhanvien

--Tạo 1 trigger tự động thực hiện 1 câu thông báo mỗi khi nhập thêm 1 bản ghi mới cho nhân
viên
Create Trigger Tr_InsertNV
On Nhanvien
For Insert
As
Begin
Raiserror ('%d Dòng này đã được thêm vào trong bảng Nhân viên',0,1,@@rowcount);
Insert into Nhanvien
values('N07',N'Nguyễn Thị Minh ','09/11/2000','P01')
End

select * from Nhanvien


--tạo 1 Trigger tự động thực hiện câu thông báo khi xóa 1 or nhiều bản ghi trên bảng
nhanvien
Alter Trigger Tr_Drop
On Nhanvien
For Delete
As
Raiserror ('%d nhân viên này đã được xóa trong bảng Nhân viên',0,1,@@rowcount)

Delete from Nhanvien where MANV='N07';


select * from Nhanvien

--vd3: Tạo 1 trigger tự động cập nhật mỗi khi có 1 cập nhật tự động trong bảng NV
Create Trigger Tr_Update
On Nhanvien
For Update
As
Raiserror ('%d dòng đã được cập nhật trong bảng Nhân Viên',0,1,@@rowcount)

Update Nhanvien set MAPHONG='P02' where MANV = 'N04'


--Vd4 thêm 1 trường tổng nhân viên cho phòng . Sau đó xóa hết nhân viên
Alter table Phong
Add TongNV int ;
Delete from Nhanvien
--Viết trigger. khi chèn một nhân viên vào cho phòng ban nào đó thì tổng số NV trong phòng
đó được tăng lên 1
Create Trigger TR_TongNV
On Nhanvien
For Insert
As
Update Phong
Set TongNV = TongNV + 1
Where Phong.MAPHONG = (select MAPHONG from inserted)

Insert into Nhanvien


values('N09',N'Nguyễn Thị Hoài Thương ','12/11/2000','P01')

Select * from Phong


Select * from Nhanvien

-- Viết trigger xóa 1 nhân viên thì tổng nhân viên sẽ thay đổi
Alter Trigger TR_DROPNV
On Nhanvien
For delete
As
Update Phong
Set TongNV = TongNV-1
where Phong.MAPHONG = (select MAPHONG from deleted)

Delete from Nhanvien


where MANV = 'N01';

-- Viết trigger xóa nhiều nhân viên thì tổng số nhân viên trong phòng sẽ thay đổi

Create Trigger Tr_DROPNNV


on Nhanvien
For Delete
As
begin
Update Phong
Set TongNV = TongNV - (select count(*) from deleted where deleted.MAPHONG =
Phong.MAPHONG)
from deleted
where deleted.MAPHONG = Phong.MAPHONG
end
delete from NHANVIEN where MANV in ('N01','N02')
Select * from Phong
Select * from Nhanvien
-- Viết trigger thay đổi phòng của nhân viên thì tổng số nhân viên trong phòng sẽ thay đổi
CREATE TRIGGER TR_CHUYENNVSANGPHONGKHAC
ON NHANVIEN
FOR UPDATE
AS
BEGIN
--GIẢM TONGNV PHÒNG CŨ
UPDATE PHONG
SET TONGNV = TONGNV - (SELECT COUNT(*) FROM deleted)
WHERE MAPHONG = (SELECT MAPHONG FROM deleted GROUP BY
MAPHONG)
--TĂNG TONGNV PHÒNG MỚI
UPDATE PHONG
SET TONGNV = TONGNV + (SELECT COUNT(*) FROM inserted)
WHERE MAPHONG = (SELECT MAPHONG FROM inserted GROUP BY
MAPHONG)
END

-- Viết trigger khi luân chuyên 1 hoặc nhiều nhân viên từ phòng này sang phòng khác thì tổng
số nhân viên sẽ thay đổi
Create Trigger TR_CHUYENNVSANGPHONGKHAC
On Nhanvien
For update
As
if UPDATE(MAPHONG)
Update Phong
Set TongNV = (Select count(*)
from Nhanvien
where Nhanvien.MAPHONG = Phong.MAPHONG)
--Chạy lệnh Update
Update Nhanvien set MAPHONG ='P02'
where MANV in ('N01','N05')
Select * from Phong
Select * from Nhanvien
--Viết hàm tính tống số nhân viên của phòng dựa trên bảng Nhânvien
if OBJECT_ID('fsonhanvien','FN') is not null
drop function fsonhanvien
go
Create function fsonhanvien (@MAPHONG char(4))
returns int
as
begin
return (Select count(*)
from Nhanvien
where Nhanvien.MAPHONG = @MAPHONG)
End

select dbo.fsonhanvien('P02') As [Tổng số nhân viên]


--Viết hàm tính tổng nhân viên khi nhập vào 3 phòng
if OBJECT_ID('fsoNnhanvien','FN') is not null
drop function fsoNnhanvien
go
Create function fsoNnhanvien (@map1 char(4),@map2 char(4),@map3 char(4))
returns int
as
begin
return (Select count(*)
from Nhanvien
where Nhanvien.MAPHONG in (@map1,@map2,@map3))
End
--Return table
Create function Table_NV (@Maphong char(4))
returns @ketqua table(Manv char(4),Hoten nvarchar(40))
As
begin
insert into @ketqua
select Manv,Hoten
from Nhanvien
where MAPHONG = @Maphong
return;
end

select * from Table_NV('P03')


select * from Nhanvien

-- Datepart(Datepart,Date)---
select DATEPART(YY,GETDATE()) as [Năm]
select DATEPART(DD,GETDATE()) as [Ngày]
select DATEPART(DW,'2021/10/16') as [Thứ]
select DATEPART(QQ,GETDATE()) as [Quý]
select DATEPART(YY,GETDATE()) as [Năm]
select DATEPART(DY,GETDATE()) as [Ngày của năm]
select DATEPART(WW,GETDATE()) as [Tuần của năm]
--Dateiff(Datepart,Startdate,enddate)--
select DATEDIFF(MM,GetDate(),'2022/01/10') as [Số tháng]
select DATEDIFF(DD,GetDate(),'2022/01/10') as [Số Ngày]
select DATEDIFF(HH,GetDate(),'2022/01/10') as [Số giờ]
select DATEDIFF(WW,GetDate(),'2022/01/10') as [Số tuần]

--Datename(nhập vào ngày cho ra thứ)


Select DATENAME(DW,'2022/10/28') As [Thứ mấy]

--Bài tập 1 viết hàm trả về ngày của tháng năm do người dùng truyền vào
GO
CREATE FUNCTION F_MONTH_YY(@M INT, @Y INT)
RETURNS INT
AS
BEGIN
IF @M=2
IF (@Y%400=0) OR (@Y%4=0 AND @Y%100!=0)
RETURN 29;
RETURN 28;
IF @M IN (1,3,5,7,8,10,12) RETURN 31
RETURN 30;
END

select dbo.F_MONTH_YY(2,2021)

--Viết hàm xác định thứ trong tuần khi truyền vào biến ngày
Create function dbo.Datepar(@test date)
returns nvarchar(10)
As
Begin
Return case(Datepart(DW,@test))
WHEN 1 THEN N'Chủ nhật'
WHEN 2 THEN N'Thứ hai'
WHEN 3 THEN N'Thứ ba'
WHEN 4 THEN N'Thứ tư'
WHEN 5 THEN N'Thứ năm'
WHEN 6 THEN N'Thứ sáu'
WHEN 7 THEN N'Thứ bảy'
else N'Không hợp lệ'
end
End

select dbo.Datepar('2021/07/26') As [Day]


-- BÀI TẬP 1: MỞ 1 CỬA SỔ LỆNH ADMIN ĐỂ TẠO 3 USER: A, B, C
--Tạo user A
Create login A with password = '123456';
Go
use QLNV;
Go
Create user A for login A;

--Tạo user B
Create login B with password = '123456';
Go
use QLNV;
Go
Create user B for login B;

--Tạo user C
Create login C with password = '123456';
Go
use QLNV;
Go
Create user C for login C;
-- PHÂN QUYỀN CHO 3 USER
-- A, B CÓ TOÀN QUYỀN TRÊN DB QLNV (Phân quyền db_owner cho user A,B)
-- C KHÔNG CÓ QUYỀN GÌ TRÊN DB QLNV,NGOÀI QUYỀN ĐƯỢC XEM (C có
quyền public)
-- LOGIN VÀO USER TƯƠNG ỨNG ĐỂ CẤP QUYỀN
-- A: CẤP QUYỀN XEM DỮ LIỆU CHO C TRÊN BẢNG NHÂN VIÊN
Grant select
on Nhanvien To C
-- B: CẤP QUYỀN XEM VÀ BỔ SUNG DỮ LIỆU TRÊN BẢNG NHÂN VIÊN CHO C
Grant select,insert
on Nhanvien To C
-- NHẬN XÉT: C LÚC NÀY CÓ NHỮNG QUYỀN GÌ? ( C lúc này có quyền Select và
insert)
-- B HỦY QUYỀN CỦA C (Thì lúc này C còn quyền Select từ A)
/*BT:
1.Tạo 2 login và user có tên: NSD1, NSD2
2.Cài đặt server role và DB Role cho 2 NSD trên
3.Cấp quyền cho 2 NSD
+NSD1 được quyền select, nhưng không được insert, update, delete trên các bảng
+NSD2 được quyền insert, select trên bảng phòng, k được update,delete trên NV
*/
--1. Tạo login và user NSD1,NSD2
Create login NSD1 with password = '123456'
use QLNV
Create user NSD1 for login NSD1

Create login NSD2 with password = '123456'


use QLNV
Create user NSD2 for login NSD2
--2. Cài đặt server role và DB Role cho 2NSD
---NSD1 server role (Dbcreate) , DB Role (Db_Datareader)
---NSD2 server role (Dbcreate) , Db Role (public)

--3. Cấp quyền


--NSD1 Select, không có quyền insert, update, delete trên các bảng
Grant Select
on Nhanvien
To NSD1
Grant Select
on Phong
To NSD1
--NSD2 Insert,select ,hông được update,delete trên bảng NV
Grant Insert,select
On Nhanvien
To NSD2

Lecture Questions
Lecture 7 – Design Physical File

1. Consider the following tw relations for Millennium College:


STUDENT (Student_ID, Student_Name, Campus_Address, GRA)
REGISTRATION (Student_ID, Course_ID, Grade)

SELECT STUDENT.STUDENT_ID, STUDENT_NAME, COUSE_ID, GRADE


FROM STUDENT, REGISTRATION
WHERE (STUDENT.STUDENT_ID=REGISTRATION.STUDENT_ID) AND (GRA>3)
ORDER BY STUDENT_NAME;

a. On what attributes should indexes be defined to speed up this query?


Give the reasons for each attribute selected?
We should choose attribute Student_ID, Student_Name , GRA .
b. Write SQL commands to create indexes for each attribute you identified
in part a.
Create unique index IDINDEX
On STUDENT(Student_ID)

Create clustered index NAMEINDEX


On STUDENT(Student_Name)

Create clustered index GRAINDEX


On STUDENT(GRA)
2. Consider the following schema:

EMPLOYEE(EmployeeID, EmployeeName, Age, Salary)


DEPARTMENT(DepartmentID, DepartmentName, Budget, ManagerID)
WORKS(EmployeeID, DepartmentID, time)
a. For each of the following reports, indicate any indexes that you
feel would help the report run faster as well as the type of index.
Write SQL commands to create indexes for each attribute you
identified

- For this report, I will choose the DepartmentID and


DepartmentName index to make the report run faster.
-Write Sql commands to create indexes :
Create unique index DepIDIndex
On DEPARTMENT(DepartmentID)

Create clustered index DepNameIndex


On DEPARTMENT(DepartmentName)
Did Dname Total _of_Salary

b. What is the role of the buffer manager in a DBMS? What is the


role of the disk space manager? ( ID vs Name) index

- The buffer manager is a software module of DBMS whose


responsibility is to serve to all the data requests and take decision
about choosing a buffer and to manage page replacement.
-The disk space manager (DSM) (implemented as part of the DB
class) is the component of the Mini base that takes care of the
allocation and deallocation of pages within a database.
3. Consider the following schema:

SUPPLIERS(SupplierID, SupplierName, Address)


PARTS(PartID, PartName, Color)
CATALOG(SupplierId, PartID, Cost)
a. For each of the following reports, indicate any indexes that you
feel would help the report run faster as well as the type of index.
Write SQL commands to create indexes for each attribute you
identified

-For this report, I will choose the DepartmentID and


DepartmentName index to make the report run faster.
-Write Sql commands to create indexes :
Create unique index SupIDIndex
On SUPPLIERS(SupplierID)

Create clustered index SupNIndex


On SUPPLIERS(SupplierName)
sid sname Total _of_Pid

b. What is the difference between a clustered index and an


unclustered index

-Clustered Index : A Clustered index is a type of index in which table records


are physically reordered to match the index.

-Nonclustered index: A Non-Clustered index is a special type of index in which


logical order of index does not match physical stored order of the rows on
disk.

Refer to Figure 1. For each of the following reports, indicate any indexes that
you feel would help the report run faster as well as the type of index:
a. State by products (use – specified period)

State By Products Report January 1, 2013 To March 31, 2013

State Product Description Total Quantity


Ordered

CO 8- Drawer Dresser 1

CO Entertainment Center 0

CO Oak Computer Desk 1

CO Write’s Desk 2

NY Write’s Desk 1

VA Write’s Desk 5

- Create clustered index CUSINDEX


on T_CUSTOMER (STATE)

- Create clustered index ORDERINDEX


on T_ORDER(CUSTOMER_ID)

- Create clustered index ORDERLINEINDEX


on T_ORDER_LINE(ORDER_ID, PRODUCT_ID)

- Create clustered index PROINDEX


on T_PRODUCT (PRODUCT_DESCRIPTION)

b. Most fequently sold product finish in a user – specified month


Most Frequently Sold Product Finish Report March 1, 2013
to March 31, 2013

Product Finish Units Sold

Cherry 13

- Create clustered index PRODUCINDEX


On T_ PRODUCT (PRODUCT_FINISH)

c. All orders placed last month

Monthly Order Report March 1, 2013 To March 31, 2013

Order_I Order_Date Customer_ID Customer_Name


D

19 3/5/2013 4 Eastern Furniture

Order Details:

Product Description Quantity Price Exteded Price


Ordered

Cherry End Table 10 75 750

High Back Leather 5 362 1810


Chair

Order_I Order_Date Customer_ID Customer_Name


D

24 3/10/2013 1 Comtemporaty Casuals

Order Details:

Product Description Quantity Price Exteded Price


Ordered

Bookcase 4 69 276

- Create clustered index T_ORDERINDEX


On T_ORDER (CUSTOMER_ID,ORDER_DATE)
- Create clustered index T_ORDERLINEINDEX
On T_ORDER_LINE (PRODUCT_ID)
- Create clustered index T_PRODUCTINDEX
On T_PRODUCT (PRODUCT_DESCRIPTION)

d. Total products sold by product line (use-specified period)

Products sold by Product Line March 1, 2013 To March 31,


2013

Product_Line Quantity Sold - Create clustered


index T_ORDER_INDEX
Basic 200
On
Antique 15 T_ORDER
Modern 10

Classical 75

(ORDER_DATE)
- Create clustered index T_ORDER_LINE_INDEX
On T_ORDERLINE (ORDER_ID, PRODUCT_ID)
- Create clustered index T_PRODUCT_INDEX
On T_ORDER (PRODUCT_LINE_ID)

You might also like