Bài 11 THỦ TỤC VÀ HÀM pptx

53 546 0
Bài 11 THỦ TỤC VÀ HÀM pptx

Đ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

Bài 11 THỦ TỤC VÀ HÀM THỦ TỤC VÀ HÀM  Khái niệm thủ tục  Các thao tác với thủ tục  Tham số bên thủ tục  Một số vấn đề khác thủ tục  Hàm  Giao tác Khái niệm thủ tục  Một thủ tục đối tượng sở liệu bao gồm tập nhiều câu lệnh SQL nhóm lại với thành nhóm với khả sau:  Có thể bao gồm cấu trúc điều khiển (IF, WHILE, FOR)  Bên thủ tục lưu trữ sử dụng biến nhằm lưu giữ giá trị tính tốn được, giá trị truy xuất từ sở liệu  Một thủ tục nhận tham số truyền vào trả giá trị thông qua tham số  Khi thủ tục lưu trữ định nghĩa, gọi thơng qua tên thủ tục, nhận tham số truyền vào, thực thi câu lệnh SQL bên thủ tục trả giá trị sau thực xong Khái niệm thủ tục Lợi ích thủ tục  Đơn giản hoá thao tác sở liệu nhờ vào khả module hoá thao tác  Thủ tục lưu trữ phân tích, tối ưu tạo nên việc thực thi chúng nhanh nhiều so với việc phải thực tập rời rạc câu lệnh SQL tương đương theo cách thông thường  Cho phép thực yêu cầu câu lệnh đơn giản thay phải sử dụng nhiều dịng lệnh SQL Điều làm giảm thiểu lưu thông mạng  Thay cấp phát quyền trực tiếp cho người sử dụng câu lệnh SQL đối tượng sở liệu, ta cấp phát quyền cho người sử dụng thông qua thủ tục lưu trữ, nhờ tăng khả bảo mật hệ thống Phân loại thủ tục  Các loại Procedures  User-defined  System  Temporary  Remote  Extended Phân loại thủ tục  System sp: lưu trữ CSDL master Các thủ tục có tên bắt đầu sp Chúng đóng vai trị khác tác vụ cung cấp SQL Server  Local sp: lưu trữ CSDL người dùng, thực thi tác vụ CSDL chứa Được người sử tạo hay từ sp hệ thống  Temporary sp: giống local sp hữu kết nối tạo bị đóng Nó nằm CSDL TempDB Có loại temporary sp: local (private), Global, sp tạo trực tiếp TempDB  Extended sp: thủ tục tạo từ ngơn ngữ lập trình khác (khơng phải SQL Server) triển khai tính thủ tục SQL Server Các thủ tục có tên bắt đầu xp  Remote sp: thủ tục gọi thực thi từ server từ xa Ví dụ System Stored Procedures sp_stop_job sp_databases sp_server_info sp_stored_procedures System stored procedures sp_password sp_tables sp_start_job sp_configure sp_help sp_helptext Ví dụ System Stored Procedures System Store Procedure Sp_databases Sp_server_info Sp_store_procedure Sp_table Description Lists all the databases available on the server Lists server information, such as, character set, version, and sort order Lists all the stored procedures avaible in the current environment Lists all the objects that can be queried in the current environment Sp_start_job Starts an automated task immediately Sp_stop_job Stops an automated task that is running Ví dụ System Stored Procedures System Store Procedure Description Sp_password Change the password for a login account Sp_configue Changes the SQL Server global configuration option When used without options, display the current server settings Displays information about any database object Displays the actual text for a rule, a default, or an un-define function, trigger or view Sp_help Sp_helptext A SCALES UDFs (without parameter)  Example : Hàm trả tổng tiền khách hàng có mã TOMSP Create function Tongtien() Returns money AS Begin Declare @tong money Select @tong = sum(unitprice*Quantity) from orders o, [Order Details] d where o.orderid = d.orderid and customerid = 'TOMSP' Return @tong End print 'Tong = ' +convert(char(10),dbo.tongtien()) select dbo.tongtien() as Tong A SCALES UDFs (with parameter)  A scalar UDF   A scalar UDF with Parameter as functions get values from outside The basic syntax is: CREATE FUNCTION [owner_name.]function_name ([{@parameter_name [AS] data_type [=default]} [ ,…n ]]) RETURNS scalar_return_data_type [WITH { ENCRYPTION | SCHEMABINDING } [ [,] n] ] [ AS ] BEGIN function_body RETURN scalar_expression END A SCALES UDFs (with parameter)  Example : Hàm trả tổng hai số Create function tong(@so1 int, @so2 int) Returns int as Begin Return @so1+@so2 end Thuc hien ham Declare @a int, @b int Set @a = set @b =6 print 'Tong cua '+convert(char(5),@a) +' + '+ convert(char(5),@b)+'='+convert(char(5),dbo.tong(@a,@b)) select dbo.tong(@a,@b) as tong A SCALES UDFs (with parameter)  Example : Hàm trả tổng tiền khách hàng Create function TongtienTS(@makh nchar(5)) Returns money AS Begin Declare @tong money Select @tong = sum(unitprice*Quantity) from orders o, [Order Details] d where o.orderid = d.orderid and customerid = @makh Return @tong End declare @ma nchar(5) Set @ma = 'TOMSP' print 'Tong = ' +convert(char(10),dbo.tongtients(@ma)) select dbo.tongtients(@ma) as Tong A SCALES UDFs (with parameter) Example : Hàm trả thứ tiếng việt Create function thu(@ngay datetime) Returns varChar(10) As Begin Declare @t varchar(10), @d tinyint Set @d = datepart(dw,@ngay) Set @t = case When @d = then 'Chu Nhat' When @d = then 'Hai' When @d = then 'Ba' When @d = then 'Tu' When @d = then 'Nam' When @d = then 'Sau' When @d = then 'Bay' end Return @t end A SCALES UDFs (with parameter) Example : Hàm trả thứ tiếng việt declare @ngaysinh datetime Set @ngaysinh = getdate() hay '04/12/1982'-Print 'Ban sinh vao Thu '+dbo.thu(@ngaysinh) + ' Ngay '+ convert(char(3),day(@ngaysinh)) + ' thang ' + Convert(char(3), month(@ngaysinh))+ ' nam ' +convert(char(5),year(@ngaysinh)) thuc hien voi cau lenh Select select employeeid, LastName +' '+FirstName as Hoten, thu =dbo.thu(birthdate) from Employees select employeeid, LastName +' '+FirstName as Hoten, [Thu Ngay Thang Nam Sinh] ='Thu '+dbo.thu(birthdate) + ' Ngay '+ convert(char(2),day(birthdate)) + ' thang ' + Convert(char(2), month(birthdate))+ ' nam ' +convert(char(4),year(birthdate)) from Employees A SCALES UDFs (with parameter) Example : Hàm trả Tổng tiền sản phẩm Create function TotalAmount (@Unitprice money, @quantity Smallint,@Discount real) Returns Money As Begin Return (@Unitprice * @Quantity)*(1-@discount) End Su dung Select Productid, Total = dbo.TotalAmount(Unitprice,Quantity,Discount) From [Order Details] Where Orderid =10250 The table-valued UDFs  The table-valued UDFs are split into two subtypes: inline and multistatement table-valued  An inline table-valued UDF:  It can be seen as a view with parameters They execute one SELECT statement, as in a view, but can include parameters, like a stored procedure  The basic syntax is: CREATE FUNCTION [owner_name.]function_name ([{@parameter_name [AS] data_type [=default]} [ ,…n ]]) RETURNS TABLE [WITH { ENCRYPTION | SCHEMABINDING } [ [,] n] ] [AS] RETURN [(] select-stmt [)] The table-valued UDFs Example 1: Cho biết tổng số hóa đơn khách hàng  CREATE FUNCTION CountOrderCust (@cust varchar(5)) RETURNS TABLE AS RETURN (Select CustomerID, count(orderid)as countOrder From orders Where customerID like @cust Group by customerID ) Go  Thi hành (không cần tên đầy đủ) Select * from CountOrderCust('A%' ) The table-valued UDFs Example : trả tổng số lượng sản phẩm theo lọai hàng CREATE FUNCTION SalesByCategory(@Categoryid Int) RETURNS TABLE AS RETURN (SELECT c.CategoryName, P ProductName, SUM(Quantity) AS TotalQty FROM Categories c INNER JOIN Products p ON c.CategoryID= p CategoryID INNER JOIN [Order Details] od ON p.ProductID = od.ProductID WHERE c.CategoryID= @Categoryid GROUP BY c CategoryName,p.ProductName)  Using SELECT * FROM SalesByCategory (1)  The table-valued UDFs  Multistatement Table-valued UDF are the most complex form of UDF This type of function builds the result set from one or many SELECTstatements  The basic syntax is: CREATE FUNCTION [owner_name.]function_name ([{@parameter_name [AS] data_type [=default]} [ ,…n ]]) RETURNS @return_variable TABLE ({column_definition | table_constraint} [ ,…n ]) [WITH { ENCRYPTION | SCHEMABINDING } [ [,] n] ] [AS] BEGIN function_body RETURN END The table-valued UDFs Example CREATE FUNCTION CountOrderCust() RETURNS @fn_CountOrderCust TABLE (OrderIdent tinyint Not null, Cust varchar(5) ) AS Begin Insert @fn_CountOrderCust Select Count(orderid),CustomerId From Orders Group by customerid Return end Thi h ành Select * from CountOrderCu() The table-valued UDFs  Example CREATE FUNCTION Contacts(@suppliers bit=0) RETURNS @Contacts TABLE (ContactName nvarchar(30), Phone nvarchar(24), ContactType nvarchar(15)) AS BEGIN INSERT @Contacts SELECT ContactName, Phone, 'Customer' FROM Customers INSERT @Contacts SELECT FirstName + ' ' + LastName, HomePhone, 'Employee' FROM Employees IF @Suppliers=1 INSERT @Contacts SELECT ContactName, Phone, 'Supplier‘ FROM Suppliers RETURN END  Using SELECT * FROM CONTACTS(1) ORDER BY ContactName Using UDFs Depending on the UDF type, the execution call is different  A scalar UDF is always called by a two-component name: owner.functionname Example: SELECT ProductID, Total=dbo.TotalAmount(UnitPrice, Quantity, Discount) FROM [Order details] WHERE OrderID=10250  A scalar UDF can be used where an expression may be used: in the select list of a SELECT statement, as in the above example, or even in a CREATE TABLE statement Example: CREATE TABLE [Order Details] ( OrderID int NOT NULL , ProductID int NOT NULL , UnitPrice money NOT NULL DEFAULT (0), Quantity smallint NOT NULL DEFAULT (1), Discount real NOT NULL DEFAULT (0), Total AS dbo.TotalAmount(UnitPrice, Quantity, Discount)) Using UDFs A table-valued UDF may be called with a one- or two-component name, as in the following example:  SELECT * FROM Contacts(1) ORDER BY ContactName - if a table-valued function has no parameters, you must still use parentheses: -If parameters have default values, they cannot be skipped or ignored in the function call You have to use the DEFAULT keyword SELECT * FROM Contacts() ORDER BY ContactName ...THỦ TỤC VÀ HÀM  Khái niệm thủ tục  Các thao tác với thủ tục  Tham số bên thủ tục  Một số vấn đề khác thủ tục  Hàm  Giao tác Khái niệm thủ tục  Một thủ tục đối tượng sở... thơng qua tên thủ tục, nhận tham số truyền vào, thực thi câu lệnh SQL bên thủ tục trả giá trị sau thực xong Khái niệm thủ tục Lợi ích thủ tục  Đơn giản hoá thao tác sở liệu nhờ vào khả module... RAISERROR (50100, 16, 1, @Productid) RETURN 50100 END EXEC SearchPro 111 11 Định nghĩa Hàm  Hàm tương tự thủ tục bao gồm phát biểu T-SQL  Hàm dùng trong:    Danh sách chọn câu lệnh Select giá trị

Ngày đăng: 27/06/2014, 06:20

Từ khóa liên quan

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

  • Đang cập nhật ...

Tài liệu liên quan