Presentation is loading. Please wait.

Presentation is loading. Please wait.

STORED PROCEDURES AND FUNCTION (9.6.1)

Similar presentations


Presentation on theme: "STORED PROCEDURES AND FUNCTION (9.6.1)"— Presentation transcript:

1 STORED PROCEDURES AND FUNCTION (9.6.1)
Chapter 9 (tt) STORED PROCEDURES AND FUNCTION (9.6.1)

2 Introduction Stored procedure (SP): is a segment of code which contains declarative or procedural SQL statements. A stored procedure is resided in the catalog of the database server so we can call it from a trigger, another stored procedure or even from client applications. Stored procedures are essentially functions that you can create in the database and reuse. They can take input parameters and then return a result

3 Stored procedures type
System SP (sp): is stored in the Master database, but can be executed in any database without using its full name. sp_helptext: Prints the text of a rule, a default, or an unencrypted stored procedure, user-defined function, trigger, computed column, or view. Example : master.dbo.sp_helptext sp_help: Reports information about a database object sp_depends: Displays information about database object dependencies the view(s), trigger(s), and procedure(s)—in the database that depend on a specified table or view,

4 Stored procedures type
Extended SP (xp): is created from other languages (C++,...) and used as a procedure of SQL Server User_defined : Local sp: is an object in the database to execute the tasks. It can be created in master db. Temporary sp: local (with the name begun by #) and global (with the name begun by ##).

5 Create stored procedures
Syntax: CREATE PROC [ EDURE ] procedure_name [ ; number ] [ data_type } [ VARYING ] [ = default ] [ OUTPUT ] ] [,...n ] [ WITH  { RECOMPILE | ENCRYPTION | RECOMPILE, ENCRYPTION } ] [ FOR REPLICATION ] AS sql_statement [ ...n ]

6 Create stored procedures
Example: CREATE PROCEDURE OrderSummary AS SELECT Ord.EmployeeID, SummSales=SUM(OrDet.UnitPrice*OrDet.Quantity) FROM Orders AS Ord JOIN [Order Details] AS OrDet ON (Ord.OrderID = OrDet.OrderID) GROUP BY Ord.EmployeeID

7 Execute stored Procedures
Execute: Executes user-defined function, a system procedure, a user-defined stored procedure, or an extended stored procedure. Syntax: [ [ EXEC [ UTE ] ] = ]     { procedure_name [ ;number ] | @procedure_name_var     }     [ = ] { value [ OUTPUT ] | [ DEFAULT ] ] [,...n ] [ WITH RECOMPILE ]

8 Execute stored Procedures
Example: EXECUTE dbo.overdueOrders EXECUTE ProductName [ ; number ] [<parameter>[, …n][ OUTPUT ]]

9 Modify stored Procedures
Syntax: ALTER PROCEDURE procedure_name [WITH option] AS sql_statement [...n]

10 Modify stored Procedures
Example: ALTER PROC dbo.overdueOrders AS SELECT CONVERT(CHAR(8), RequiredDate,1) RequiredDate, CONVERT(CHAR(8), orderDate,1) orderDate, orderId, Customerid, EmployeeID FROM dbo.orders WHERE RequiredDate<GETDATE()and shippeddate is null ORDER BY RequiredDate

11 Delete stored Procedures
Syntax: DROP PROC owner.stored_procedure_name

12 Using parameter in stored Procedures
Input parameter: CREATE PROCEDURE procedure_name data_type] [=default_value] [WITH option] AS sql_statement [...n]

13 Using parameter in stored Procedures
Example 1: CREATE PROC dbo.MovieByRating @rating varchar(5) = NULL AS SELECT rating , title FROM movie WHERE rating ORDER BY title

14 Using parameter in stored Procedures
Example 2 : CREATE PROC sp_name @parameter data_type =value AS IF @parameter IS NULL BEGIN PRINT ‘Message Line 1’ PRINT ‘Message Line 2’ RETURN END SELECT statement GO

15 Using parameter in stored Procedures
Output parameter: CREATE PROCEDURE procedure_name data_type] [=default_value] OUTPUT [WITH option] AS sql_statement [...n]

16 Using parameter in stored Procedures
Example: CREATE PROC count_row @movie_count int OUTPUT AS SELECT @movie_count = COUNT(*) FROM Movie GO Sp execution with output parameter: a variable must be declared to stored the return value of the output parameter DECLARE @num int EXEC count_row @num OUTPUT SELECT @num

17 Errors management sp_addmessage: Stores a new user-defined error message in an instance of the SQL Server Database Engine. Messages can be viewed by using the sys.messages. Syntax: sp_addmessage ] msg_id , ] severity , ] 'msg' [ , ] 'language' ] [ , ] { 'TRUE' | 'FALSE' } ] [ , ] 'replace' ]

18 Errors management Example: Create an error message by sp_addmessage
EXEC sp_addmessage @msgnum = 50001, @severity = 10, @msgtext=‘Cannot delete customer. Customer has orders .’, @withlog = ‘true’ GO

19 Errors management VD: Display an error message when delete a customer
CREATE PROC DeleteCust @cust_num nvarchar(5) = null AS IF EXISTS (SELECT customerID FROM Orders WHERE customerID BEGIN RAISERROR (50001, 10, 1) RETURN END DELETE FROM Customers WHERE customerID GO

20 Errors management Returns an error number if the previous statement encountered an error. Example: USE AdventureWorks2008R2; GO UPDATE HumanResources.EmployeePayHistory SET PayFrequency = 4 WHERE BusinessEntityID = 1; IF = 547 PRINT N'A check constraint violation occurred.';

21 Errors management and Use to validate the operation of an UPDATE statement. The value of is checked for any indication of an error. The value of is used to ensure that the update was successfully applied to a row in the table.

22 FUNCTION System function:
aggregate funtion: avg(), count(), count(*), sum(), max(), min(),... Other function: getdate(), month(), upper(), User-defined function: Allow you to define your own T-SQL functions that can accept zero or more parameters and return a single scalar data value or a table data type.

23 FUNCTION There are 3 type User-defined function:
Scalar: return a single value, based on the input value. Multi-statement Table-valued: return a set of row Inline Table-valued: return a set of row

24 FUNCTION Scalar function:
CREATE  FUNCTION [ owner_name. ] function_name ( [ [AS] scalar_parameter_data_type [= default ] } [ ,...n ] ] ) RETURNS scalar_return_data_type. [WITH < function_option> [ [,] ...n] ] [AS ] BEGIN     function_body     RETURN scalar_expression END

25 FUNCTION Example: CREATE FUNCTION dbo.OrderNum (@monthOrd tinyint )
RETURNS tinyint AS BEGIN tinyint = count(orderid) FROM Orders WHERE END GO

26 FUNCTION Execute: SELECT dbo.OrderNum(7)
Function can be used in the “Where” clause Select orderid from orders where dbo.OrderNum(7) > 50 and month(orderdate)=7

27 FUNCTION Table-valued Functions
CREATE FUNCTION [ owner_name. ] function_name [AS] scalar_parameter_data_type [= default ] } [,...n ] ]) RETURNS TABLE [WITH < function_option > [ [,] ...n ] ] [AS ] RETURN [(] select-stmt [)] Một hàm inline table-valued: Nó có thể được xem như là một View có tham số. Chúng thực thi một câu lệnh Select như trong một view nhưng có thể bao gồm các tham số, giống như thủ tục.

28 FUNCTION Example: 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 GROUP BY c. CategoryName,p.ProductName)

29 FUNCTION Multistatement Table-valuesd
CREATE FUNCTION [owner_name.]function_name [AS] data_type [=default]} [ ,…n ]]) TABLE ({column_definition | table_constraint} [ ,…n ]) [WITH { ENCRYPTION | SCHEMABINDING } [ [,] ...n] ] [AS] BEGIN function_body RETURN END

30 FUNCTION Example: CREATE FUNCTION Contacts(@suppliers bit=0)
TABLE (ContactName nvarchar(30), Phone nvarchar(24), ContactType nvarchar(15)) AS BEGIN SELECT ContactName, Phone, 'Customer' FROM Customers SELECT FirstName + ' ' + LastName, HomePhone, 'Employee' FROM Employees SELECT ContactName, Phone, 'Supplier‘ FROM Suppliers RETURN END

31 FUNCTION Execute: SELECT * FROM CONTACTS(1) ORDER BY ContactName


Download ppt "STORED PROCEDURES AND FUNCTION (9.6.1)"

Similar presentations


Ads by Google