Bài tập CSDL SQL

30 1.4K 0
Bài tập CSDL SQL

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Module Tìm hiểu Cơ sở liệu AdventureWork2008 - Tạo quản trị sở liệu – Database file – File group Mục tiêu: - Tìm hiểu sở liệu AdventureWork2008 Tạo quản trị sở liệu Database Tạo quản lý Table (Bảng liệu) Tạo lược đồ quan hệ (Relationship Diagram) Tạo, sửa, xóa áp dụng kiểu liệu SQL Server 2008 Biết số thủ tục trợ giúp database Datatype - Xây dựng ràng buộc (constraint) cho bảng - Thêm, sửa, xóa truy vấn liệu Mô tả CSDL AdventureWork2008: Gồm lược đồ • • • • • • Dbo Humanresource Person Production Purchasing Sales AdventureWorks sở liệu mẫu tạo để sử dụng giảng dạy phiên Microsoft SQL Server AdventureWorks sở liệu quản lý bán hàng công ty đa quốc gia sản xuất bán mặt hàng kim loại xe đạp thể thao đến thị trường Bắc Mỹ, châu Âu châu Á Cơ sở hoạt động nằm Bothell, Washington, nhân viên họ đội bán hàng khu vực bố trí khắp sở thị trường họ Cơng ty tìm kiếm để mở rộng thị phần cách nhắm đến khách hàng tốt họ, mở rộng sản phẩm sẵn có thơng qua trang web bên Tổ chức ý nghĩa lược đồ CSDL Schema Contains objects related to Examples HumanResources Employees of Adventure Works Cycles Employee Table Department Table Person Contact Table Address Table StateProvince Table Names and addresses of individual customers, vendors, and employees I Production Products manufactured and sold by Adventure Works Cycles BillOfMaterials Table Product Table WorkOrder Table Purchasing Vendors from who parts and products are purchased PurchaseOrderDetail Table PurchaseOrderHeader Table Vendor Table Sales Customers and sales-related data Customer Table SalesOrderDetail Table SalesOrderHeader Table Thực thao tác sở liệu AdventureWorks2008 Tạo diagram gồm bảng liên quan đến Customer Product hình trang sau SalesPerson (Sales) BusinessEntityID TerritoryID SalesQuota Bonus CommissionPct SalesYTD SalesLastYear rowguid ModifiedDate ProductCategory (Production) ProductCategor SalesTerritory (Sales) Name TerritoryID rowguid Name ModifiedDate CountryRegionCode [Group] SalesYTD SalesLastYear CostYTD CostLastYear ProductSubcategory (Production) rowguid ProductSubcategoryID ModifiedDate ProductCategoryID Name rowguid ModifiedDate Store (Sales) Customer (Sales) BusinessEntityID StoreID Name TerritoryID SalesPersonID AccountNumber Demographics rowguid rowguid ModifiedDate Product (Production) ModifiedDate WeightUnitMeasureCode Weight DaysToManufacture ProductLine StartDate Style BusinessEntity (Person) EndDate ProductSubcategoryID BusinessEntityID ProductModelID rowguid SellStartDate ModifiedDate SellEndDate DiscontinuedDate rowguid ProductVendor (Purchasing) SalesOrderHeader (Sales) SalesOrderID RevisionNumber OrderDate DueDate ShipDate Status OnlineOrderFlag SalesOrderNumber ProductID Vendor (Purchasing) BusinessEntityID StartDate AverageLeadTime AccountNumber EndDate StandardPrice Name ListPrice LastReceiptCost CreditRating ModifiedDate LastReceiptDate PreferredVendorStatus MinOrderQty ActiveFlag MaxOrderQty PurchasingWebService OnOrderQty ModifiedDate UnitMeasureCode PurchaseOrderNumber ModifiedDate AccountNumber CustomerID SalesPersonID Employee (HumanResources) BusinessEntityID SalesOrderDetail (Sales) NationalIDNumber LoginID SalesOrderID OrganizationNode SalesOrderDetailID CarrierTrackingNumber OrderQty ProductID SpecialOfferID UnitPrice UnitPriceDiscount LineTotal rowguid ModifiedDate PurchaseOrderHeader (Purchasing) PurchaseOrderID RevisionNumber Status EmployeeID VendorID ShipMethodID OrderDate OrganizationLevel JobTitle BirthDate MaritalStatus Gender HireDate SalariedFlag VacationHours ShipDate SubTotal TaxAmt Freight TotalDue ModifiedDate EmployeeDepartmentHistory (HumanResources) BusinessEntityID DepartmentID ShiftID StartDate EndDate PurchaseOrderDetail (Purchasing) PurchaseOrderID PurchaseOrderDetailID DueDate OrderQty ProductID UnitPrice LineTotal ReceivedQty RejectedQty StockedQty ModifiedDate ProductListPriceHistory (Production) ProductID BusinessEntityID ModifiedDate ProductCostHistory (Production) ProductID Class StandardCost ModifiedDate Tìm hiểu field liên kết bảng (Khóa khóa ngoại) [Production].[Product] [Person].[BusinessEntity] [Production].[ProductCostHistory] [Sales].[Store] [Production].[ProductListPriceHistory] [Sales].[Customer] [Production].[ProductSubcategory] [Sales].[SalesTerritory] [Production].[ProductCategory] [Sales].[SalesPerson] [Purchasing].[PurchaseOrderDetail] [Sales].[SalesOrderHeader] [Purchasing].[PurchaseOrderHeader] [Sales].[SalesOrderDetail] [Purchasing].[Vendor] [HumanResources].[Employee] [Purchasing].[ProductVendor] [HumanResources].[EmployeeDepartmentHistory] Sử dụng T-SQL tạo sở liệu tên SmallWorks, với file group tên SWUserData1 SWUserData2, lưu theo đường dẫn T:\Hoten\tentaptin CREATE DATABASE SmallWorks ON PRIMARY ( NAME = 'SmallWorksPrimary', FILENAME = 'T:\Hoten\SmallWorks.mdf', SIZE = 10MB, FILEGROWTH = 20%, MAXSIZE = 50MB ), FILEGROUP SWUserData1 ( NAME = 'SmallWorksData1', FILENAME = 'T:\Hoten\SmallWorksData1.ndf', SIZE = 10MB, FILEGROWTH = 20%, MAXSIZE = 50MB ), FILEGROUP SWUserData2 ( NAME = 'SmallWorksData2', FILENAME = 'T:\Hoten\SmallWorksData2.ndf', SIZE = 10MB, FILEGROWTH = 20%, MAXSIZE = 50MB ) LOG ON ( NAME = 'SmallWorks_log', FILENAME = 'T:\Hoten\SmallWorks_log.ldf', SIZE = 10MB, FILEGROWTH = 10%, MAXSIZE = 20MB ) Dùng SSMS để xem kết quả: Click phải tên CSDL vừa tạo a Chọn filegroups, quan sát kết quả: • Có filegroups, liệt kê tên filegroup • Filegroup mặc định gì? b Chọn file, quan sát có database file? Dùng T-SQL tạo thêm filegroup tên Test1FG1 SmallWorks, sau add thêm file filedat1.ndf filedat2.ndf dung lượng 5MB vào filegroup Test1FG1 Dùng SSMS xem kết Dùng T-SQL tạo thêm một file thứ cấp filedat3.ndf dung lượng 3MB filegroup Test1FG1 Sau sửa kích thước tập tin lên 5MB Dùng SSMS xem kết Dùng T-SQL xóa file thứ cấp filedat3.ndf Dùng SSMS xem kết Xóa filegroup Test1FG1? Bạn có xóa khơng? Nếu khơng giải thích? Muốn xóa bạn phải làm gì? Xem lại thuộc tính (properties) CSDL SmallWork cửa sổ thuộc tính properties thủ tục hệ thống sp_helpDb, sp_spaceused, sp_helpfile Quan sát cho biết trang thể thông tin gì? Tại cửa sổ properties CSDL SmallWork, chọn thuộc tính ReadOnly, sau đóng cửa sổ properies Quan sát màu sắc CSDL Dùng lệnh T-SQL gỡ bỏ thuộc tính ReadOnly đặt thuộc tính cho phép nhiều người sử dụng CSDL SmallWork Trong CSDL SmallWork, tạo bảng theo cấu trúc sau: CREATE TABLE dbo.Person ( PersonID int NOT NULL, FirstName varchar(50) NOT NULL, MiddleName varchar(50) NULL, LastName varchar(50) NOT NULL, EmailAddress nvarchar(50) NULL ) ON SWUserData1 -CREATE TABLE dbo.Product ( ProductID int NOT NULL, ProductName varchar(75) NOT NULL, ProductNumber nvarchar(25) NOT NULL, StandardCost money NOT NULL, ListPrice money NOT NULL ) ON SWUserData2 10 Chèn liệu vào bảng trên, lấy liệu từ bảng Person bảng Product AdventureWorks2008 (lưu ý: rõ tên sở liệu lược đồ), dùng lệnh Select Into Dùng lệnh select* để xem liệu bảng Person bảng Product SmallWorks 11 Dùng SSMS, detach sở liệu SmallWorks khỏi phiên làm việc SQL 12 Dùng SSMS, Attach sở liệu SmallWorks vào SQL Module Thao tác liệu Mục tiêu: (Phần SV tự thực hành nhà, nộp làm buổi học kế tiếp)  Ôn lại cấu trúc câu lệnh select có lệnh nhóm, subquery  Thực loại merge Query, Pivot query I) Câu lệnh SELECT sử dụng hàm thống kê với mệnh đề Group by Having 1) Liệt kê danh sách hóa đơn (SalesOrderID) lặp tháng năm 2008 có tổng tiền >70000, thông tin gồm SalesOrderID, Orderdate, SubTotal, SubTotal =sum(OrderQty*UnitPrice) 2) Đếm tổng số khách hàng tổng tiền khách hàng thuộc quốc gia có mã vùng US (lấy thơng tin từ bảng SalesTerritory, Sales.Customer, Sales.SalesOrderHeader, Sales.SalesOrderDetail) Thông tin bao gồm TerritoryID, tổng số khách hàng (countofCus), tổng tiền (Subtotal) với Subtotal = SUM(OrderQty*UnitPrice) 3) Tính tổng trị giá hóa đơn với Mã theo dõi giao hàng (CarrierTrackingNumber) có ký tự đầu 4BD, thông tin bao gồm SalesOrderID, CarrierTrackingNumber, SubTotal=sum(OrderQty*UnitPrice) 4) Liệt kê sản phẩm (product) có đơn giá (unitPrice)5, thông tin gồm ProductID, name, AverageofQty 5) Liệt kê cơng việc (JobTitle) có tổng số nhân viên >20 người, thơng tin gồm JobTitle, countofPerson=count(*) 6) Tính tổng số lượng tổng trị giá sản phẩm nhà cung cấp có tên kết thúc ‘Bicycles’ tổng trị giá >800000, thông tin gồm BusinessEntityID, Vendor_name, ProductID, sumofQty, SubTotal (sử dụng bảng [Purchasing].[Vendor] [Purchasing].[PurchaseOrderHeader] [Purchasing].[PurchaseOrderDetail]) 7) Liệt kê sản phẩm có 500 đơn đặt hàng q năm 2008 có tổng trị giá >10000, thông tin gồm ProductID, Product_name, countofOrderID Subtotal 8) Liệt kê danh sách khách hàng có 25 hóa đơn đặt hàng từ năm 2007 đến 2008, thông tin gồm mã khách (PersonID) , họ tên (FirstName +' '+ LastName as fullname), Số hóa đơn (CountOfOrders) 9) Liệt kê sản phẩm có tên bắt đầu với ‘Bike’ ‘Sport’ có tổng số lượng bán mỗi năm 500 sản phẩm, thông tin gồm ProductID, Name, CountofOrderQty, year (dữ liệu lấy từ bảng Sales.SalesOrderHeader, Sales.SalesOrderDetail, and Production.Product) 10) Liệt kê phòng ban có lương (Rate: lương theo giờ) trung bình >30, thơng tin gồm Mã phòng ban (DepartmentID), tên phòng ban (name), Lương trung bình (AvgofRate) Dữ liệu từ bảng [HumanResources].[Department], [HumanResources].[EmployeeDepartmentHistory], [HumanResources].[EmployeePayHistory] II) Subquery 1) Liệt kê sản phẩm gồm thơng tin product names product ID có 100 đơn đặt hàng tháng năm 2008 2) Liệt kê sản phẩm (ProductID, name) có số hóa đơn đặt hàng nhiều tháng 7/2008 3) Hiển thị thơng tin khách hàng có số đơn đặt hàng nhiều nhất, thông tin gồm: CustomerID, Name, CountofOrder 4) Liệt kê sản phẩm (ProductID, Name) thuộc mô hình sản phẩm áo dài tay với tên bắt đầu với “Long-Sleeve Logo Jersey”, dùng phép IN EXISTS, (sử dụng bảng Production.Product Production.ProductModel 5) Tìm mơ hình sản phẩm (ProductModelID) mà giá niêm yết (list price) tối đa cao giá trung bình tất mơ hình 6) Liệt kê sản phẩm gồm thơng tin ProductID, Name, có tổng số lượng đặt hàng >5000 (dùng In, exists) 7) Liệt kê sản phẩm (ProductID, UnitPrice) có đơn giá (UnitPrice) cao bảng Sales.SalesOrderDetail 8) Liệt kê sản phầm khơng có đơn đặt hàng thông tin gồm ProductID, Name, dùng cách Not in, not exists left join 9) Liệt kê nhân viên khơng lập hóa đơn từ sau ngày 1/5/2008, thông tin gồm EmployeeID, FirstName, LastName (dữ liệu từ bảng HR.Employees Sales.Orders) 10) Liệt kê danh sách khách hàng (customerID, name) có hóa đơn dặt hàng năm 2007 có hóa đơn đặt hàng năm 2008 III) Các loại truy vấn Union, Merge, Pivot 1) Dùng UNION hiển thị thông tin ModifiedDate Person.Person HireDate HumanResources.Employee 2) Sử dụng Merge Query, thực yêu cầu sau: a) Tạo bảng bảng tên MyOrder, gồm thuộc tính PurchaseOrderID, EmployeeID, VendorID, ShipMethodID, TotalDue, RevisionNumber, status b) Dùng lệnh Dùng lệnh Select into…chèn liệu vào bảng, lấy liệu từ bảng Purchasing.PurchaseOrderHeader c) Xóa tất dòng liệu có PurchaseOrderID khác or d) Cập nhật giá trị cột ToTalDue =1000 cho dòng có bảng MyOrder e) Dùng chức Merge để cập nhập liệu cho cột ToTalDue bảng MyOrder ToTaldue bảng Purchasing.PurchaseOrderHeader cho dòng có liệu trùng bảng, ngược lại chèn dòng khác vào bảng MyOrder 3) Tạo bảng tên UpdatedInventory chứa tổng số lượng tồn kho (QtyInventory) sản phẩm có ProductID>=900, theo cấu trúc sau: CREATE TABLE UpdatedInventory 10) Tạo view view_Department với từ khóa WITH CHECK OPTION chứa phòng thuộc nhóm có tên (GroupName) “Manufacturing” “Quality Assurance”, thông tin gồm: DepartmentID, Name, GroupName a Chèn thêm phòng ban thuộc nhóm khơng thuộc hai nhóm “Manufacturing” “Quality Assurance” thơng qua view vừa tạo Có chèn khơng? Giải thích b Chèn thêm phòng thuộc nhóm “Manufacturing” phòng thuộc nhóm “Quality Assurance” c Dùng câu lệnh select xem kết bảng Department Module Fuction stored procedure Mục tiêu: Hiểu biết cách lập trình SQL  Viết batch Tạo thực thi loại function stored procedure  Function gồm loại o Scalar function o Table value Function o MultiStatement table value Function  Stored Procedure o Tham số input output I) Batch 1) Viết batch khai báo biến @tongsoHD chứa tổng số hóa đơn sản phẩm có ProductID=’778’, @tongsoHD>500 in chuỗi “San pham 778 có 500 đơn hàng”, ngược lại tin chuỗi “San pham 778 co it don dat hang” 2) Viết đoạn Batch với tham số @makh @n chứa số hóa đơn khách hàng @makh, tham số @nam chứa năm lập hóa đơn (ví dụ @nam=2008), @n>0 in chuỗi:”Khách hàng có @n hóa đơn năm 2008” ngược lại @n=0 in chuỗi “Khách hàng khơng có hóa đơn năm 2008” 3) Viết batch tính số tiền giảm cho hóa đơn (SalesOrderID) có tổng tiền>100000, thơng tin gồm [SalesOrderID], Subtotal=sum([LineTotal]), Discount (tiền giảm), với Discount tính sau: • Những hóa đơn có Subtotal1000 - Client B: INSERT INTO Accounts (AccountID ,balance) VALUES (303,3000); COMMIT; - Client A: SELECT * FROM Accounts WHERE balance > 1000; COMMIT; Quan sát kết giải thích ... vào SQL windows authentication thông qua tài khoản user1 thực thao tác truy cập CSDL logout 6) Đăng nhập lại vào sql SQL server authentication, tài khoản sa Sử dụng TSQL 7) Tạo hai login SQL. .. Authentication cho User1, sau login vào sql Windows Authentication User1 (Khởi động máy đăng nhập hệ thống tài khoản User1 ) 3) Khởi động SQL, login vào sql Windows Authentication Kiểm tra quyền... SmallWorks 11 Dùng SSMS, detach sở liệu SmallWorks khỏi phiên làm việc SQL 12 Dùng SSMS, Attach sở liệu SmallWorks vào SQL Module Thao tác liệu Mục tiêu: (Phần SV tự thực hành nhà, nộp làm buổi

Ngày đăng: 15/03/2018, 10:39

Tài liệu cùng người dùng

Tài liệu liên quan