Giáo trình Tin học - Học SQL server 2000

SQL Server 2000 là một hệ thống quản lý cơ sở dữ liệu (Relational Database

Management System (RDBMS) ) sử dụng Transact-SQL để trao đổi dữ liệu giữa

Client computer và SQL Server computer. Một RDBMS bao gồm databases,

database engine và các ứng dụng dùng để quản lý dữ liệu và các bộ phận khác

nhau trong RDBMS.

SQL Server 2000 được tối ưu để có thể chạy trên môi trường cơ sở dữ liệu rất

lớn (Very Large Database Environment) lên đến Tera-Byte và có thể phục vụ

cùng lúc cho hàng ngàn user. SQL Server 2000 có thể kết hợp "ăn ý" với các

server khác như Microsoft Internet Information Server (IIS), E-Commerce

Server, Proxy Server.

pdf61 trang | Chia sẻ: thiennga98 | Lượt xem: 681 | Lượt tải: 0download
Bạn đang xem trước 20 trang tài liệu Giáo trình Tin học - Học SQL server 2000, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
processing when either of these columns are updated. END Nếu muốn kiểm tra nhiều columns ta có thể dùng hàm khác là Columns_Updated() . Xin xem thêm trong SQL Server Books Online để biết thêm chi tiết về cách sử dụng. Views Ðịnh nghĩa một cách đơn giản thì view trong SQL Server tương tự như Query trong Access database. View có thể được xem như một table ảo mà data của nó được select từ một stored query. Ðối với programmer thì view không khác chi so với table và có thể đặt ở vị trí của table trong các câu lệnh SQL. Ðặc điểm của View là ta có thể join data từ nhiều table và trả về một recordset đơn. Ngoài ra ta có thể "xào nấu" data (manipulate data) trước khi trả về cho user bằng cách dùng một số logic checking như (if, case...). Ví dụ: Create View OrderReport As Select OrderID, (case when [Name] is null then 'New Customer' else [Name] end )As CustomerName, ProductName, DateProcessed From Customers Right Outer Join Orders on Customers.CustomerID=Orders.CustomerID HỌC SQL SERVER 2000 56 Trong ví dụ trên ta chủ yếu trả về data từ Orders table trong PracticeDB nhưng thay vì display CustomerID vốn không có ý nhiều ý nghĩa đối với user ta sẽ display tên của customer bằng cách join với Customer table. Nếu Customer Name là Null nghĩa là tên của customer đã đặt order không tồn tại trong system. Thay vì để Null ta sẽ display "New Customer" để dễ nhìn hơn cho user. Nói chung câu lệnh SQL trong View có thể từ rất đơn giản như select toàn bộ data từ một table cho đến rất phức tạp với nhiều tính năng programming của T- SQL. View Thường Ðược Dùng Vào Việc Gì? View thường được sử dùng vào một số công việc sau: • Tập trung vào một số data nhất định : ta thường dùng view để select một số data mà user quan tâm hay chịu trách nhiệm và loại bỏ những data không cần thiết. Ví dụ: Giả sử trong table ta có column "Deleted" với giá trị là True hay False để đánh dấu một record bị delete hay không. Việc này đôi khi được dùng cho việc Audit. Nghĩa là trong một ứng dụng nào đó khi user delete một record nào đó, thay vì ta physically delete record ta chỉ logically delete bằng cách đánh dấu record là đã được "Deleted" để đề phòng user yêu cầu roll back. Như vậy chủ yếu ta chỉ quan tâm đến data chưa delete còn data đã được đánh dấu deleted chỉ được để ý khi nào cần roll back hay audit mà thôi. Trong trường hợp này ta có thể tạo ra một view select data mà Deleted=False và làm việc chủ yếu trên view thay vì toàn bộ table. • Ðơn giản hóa việc xử lý data: Ðôi khi ta có những query rất phức tạp và sử dụng thường xuyên ta có thể chuyển nó thành View và đối xử nó như một table, như vậy sẽ làm cho việc xử lý data dễ dàng hơn. • • Customize data: Ta có thể dùng view để làm cho users thấy data từ những góc độ khác nhau mặc dù họ đang dùng một nguồn data giống nhau. Ví dụ: Ta có thể tạo ra views trong đó những thông tin về customer được thể hiện khác nhau tùy login ID là normal user hay manager. • • Export và Import data: Ðôi khi ta muốn export data từ SQL Server sang các ứng dụng khác như Excel chẳng hạn ta có thể dùng view để join nhiều table và export dùng bcp. HỌC SQL SERVER 2000 57 Khi sử dụng view ta có thể select,insert, update, delete data bình thường như với một table. Ví dụ: Select * From OrderReport Where DateProcessed <'2003-01-01' Lưu ý: Trong Enterprise Edition (và Developer Edition) ta có thể tạo Index cho View như cho table. Index sẽ được bàn đến trong các bài sau. Muốn hiểu rõ hơn về bài học này bạn cần làm bài tập số 3. Như vậy trong bài này chúng ta đã tìm hiểu Trigger, View trong SQL Server và một số ứng dụng của nó. Nói chung view thường được dùng để trừu tượng hóa (abstract) hay lọc raw data (data thô) trước khi trả về cho user trong khi trigger thường được dùng để bảo đảm tính integrity của database. Exercise 1: Advanced Query Please follow those steps to practise: 1. Create a new database called PracticeDB (using Enterprise Manager (EP) or Query Analyser (QA)) 2. Create 2 tables and insert data as follows (use EP or QA) : Customers CustomerID (Int) Name (nVarChar(50)) 1 John Nguyen 2 Bin Laden 3 Bill Clinton 4 Thomas Hardy 5 Ana Tran 6 Bob Carr Orders OrderID (Int) CustomerID (Int) ProductName (nvarchar(50)) DateProcessed (datetime) 1 2 Nuclear Bomb ‘2002-12-01’ 2 3 Missile ‘2000-03-02’ 3 2 Jet-1080 ‘2003-08-03’ 4 1 Beers ‘2001-05-12’ 5 4 Asian Food ‘2002-10-04’ 6 7 Wine ‘2002-03-08’ HỌC SQL SERVER 2000 58 7 8 Milk ‘2002-05-02’ 3. Query data using Select statement with the following Join (use QA) a. Inner Join b. Left Outter Join c. Right Outer Join d. Full Outer Join e. Cross Join The result of the query must be displayed in the following format ( Hints: Based on the data supplied and your knowledge about various kind of joins guess the results then after each select compare it with your guessing to check if what you understand is correct. You also use As keyword or alias in the queries) 4. Using “Select * Into...From” statement to create a new table called “Processed Orders” and populate the new table with the data selecting from Orders table Where DateProcessed is earlier than ‘2002-10-05’. (use QA) 5. Using “Insert Into...Select” statement to get the top 1 record from “Orders” table and insert into the “ProcessedOrders” (use QA) 6. Delete a record from ProcessedOrders where the date processed is ‘2002-10-04’. (use QA) 7. Using Union to merge the two data set from Orders and ProcessedOrders into one data set. (use QA) 8. Apply Constraints (use EP or QA) a.Apply the Primary Constraint to the “ID” column in the tables b. Apply the Foreign Key Constraint in the Orders table. c. Apply the Check Constraint to the DateProcessed column so that the date is within ‘1970-01-01’ – ‘2005-01-01’ and try to insert invalid data to see if SQL rejects. d. Apply Unique Constraint to the CustomerName column of Customers 9. Back up database and Restore to somewhere else (on a different server or on the same server but with different database name) (use EP or QA) 10. Truncate and Drop the ProcessedOrders table (use QA) OrderID CustomerName ProductName DateProcessed HỌC SQL SERVER 2000 59 Exercise 2: Manipulate Data and Stored Procedure Please follow those steps to practise: 9. Use bcp to export all data from Orders table of PracticeDB to c:\Orders.txt (or to c:\Orders.csv) 10. Change some data in the c:\Orders.txt and save. Then import to Orders table from the text file using bcp 11. Import Orders.txt to Orders table using BULK INSERT 12. Create a Linked Server ‘LinkedPracticeDB’ which link to an Access database ‘PracticeDB.mdb’ (firstly you have to create an Access database similar to PracticeDB in SQL Server and input some data). Then do a select data using four- part name and OPENQUERY 13. Using ad hoc computer name with OPENROWSET and OPENDATASOURCE functions to select data from ‘PracticeDB.mdb’ 14. Create the following Cursor DECLARE @au_lname varchar(40), @au_fname varchar(20) DECLARE Employee_Cursor CURSOR FOR SELECT LastName, FirstName FROM Northwind.dbo.Employees OPEN Employee_Cursor FETCH NEXT FROM Employee_Cursor INTO @au_lname, @au_fname WHILE @@FETCH_STATUS = 0 BEGIN PRINT 'Author:' + @au_fname + ' ' + @au_lname FETCH NEXT FROM Employee_Cursor INTO @au_lname, @au_fname END CLOSE Employee_Cursor DEALLOCATE Employee_Cursor 15. Create the following stored procedure and try to execute with some values CREATE PROCEDURE AddNewOrder @OrderID smallint, @ProductName varchar(50), @CustomerName varchar(50), @Result smallint=1 Output AS DECLARE @CustomerID smallint BEGIN TRANSACTION If not Exists(SELECT CustomerID FROM Customers WHERE [Name]=@CustomerName) BEGIN HỌC SQL SERVER 2000 60 SET @CustomerID= (SELECT Max(CustomerID) FROM Customers) SET @CustomerID=@CustomerID+1 INSERT INTO Customers VALUES(@CustomerID,@CustomerName) If Exists(SELECT OrderID FROM [Orders] WHERE OrderID=@OrderID) BEGIN SELECT @Result=1 ROLLBACK TRANSACTION END Else BEGIN INSERT INTO [Orders](OrderID,ProductName,CustomerID) VALUES(@OrderID,@ProductName,@CustomerID) SELECT @Result=0 COMMIT TRANSACTION END END Else BEGIN If Exists(SELECT OrderID FROM [Orders] WHERE OrderID=@OrderID) BEGIN SELECT @Result=1 ROLLBACK TRANSACTION END Else BEGIN INSERT INTO [Orders](OrderID,ProductName,CustomerID) VALUES(@OrderID,@ProductName,@CustomerID) SELECT @Result=0 COMMIT TRANSACTION END END Print @Result Return 9. Using VB 6 or VB.NET to execute the ‘AddNewOrder’ stored procedure 10. Using xp_cmdshell extended stored procedure to send a message (xp_cmdshell ‘net send Hello’) HỌC SQL SERVER 2000 61 Exercise 3: Triggers And Views Please follow those steps to practise: 16. Create 3 triggers to audit the changes to the Orders table. Tips: • Create an audit table “aud_Orders” with the same colums as in the Orders table and 2 more colums AuditType(with values either ‘I’,’U’,’D’) and DateTimeStamp(which will record the date time stamp of changes) • Create Update Triggers (Similar to Insert,Delete) : when a record in the Orders table is updated the trigger will move the old record to the audit table(record the date time and mark it as ‘U’) 17. Create a view that shows all the orders with the following colums: OrderID,CustomerName,ProductName,DateProcessed,Status Business rules: If CustomerName is a null value “New Customer” is returned If DateProcessed is later than current date return “Pending”, if DateProcessed is ealier return “History” in Status colum. Tips: a. Using Case When ...Then statement in the view b. Using Getdate() function to get the current date time

File đính kèm:

  • pdftham khao.pdf
Giáo án liên quan