Click here to load reader

STORED PROCEDURES AND FUNCTION (9.6.1)

  • Upload
    rosina

  • View
    70

  • Download
    0

Embed Size (px)

DESCRIPTION

Chapter 9 ( tt ). STORED PROCEDURES AND FUNCTION (9.6.1). Introduction. Stored procedure (SP): is a segment of code which contains declarative or procedural SQL statements. - PowerPoint PPT Presentation

Citation preview

Data Modeling Using the Entity-Relationship (ER) Model

Chapter 9 (tt)STORED PROCEDURES AND FUNCTION (9.6.1)IntroductionStored 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 Stored procedures typeSystem 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_helptextsp_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,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 ##).

Create stored proceduresSyntax:

CREATE PROC [ EDURE ] procedure_name [ ; number ] [ { @parameter data_type } [ VARYING ] [ = default ] [ OUTPUT ]] [,...n ][ WITH { RECOMPILE | ENCRYPTION | RECOMPILE, ENCRYPTION } ] [ FOR REPLICATION ] AS sql_statement [ ...n ] Create stored proceduresExample: CREATE PROCEDURE OrderSummaryASSELECT 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

Execute stored ProceduresExecute: Executes user-defined function, a system procedure, a user-defined stored procedure, or an extended stored procedure. Syntax:

[ [ EXEC [ UTE ] ] {[ @return_status = ] { procedure_name [ ;number ] | @procedure_name_var } [ [ @parameter = ] { value | @variable [ OUTPUT ] | [ DEFAULT ] ] [,...n ] [ WITH RECOMPILE ] Execute stored ProceduresOr

Example: EXECUTE dbo.overdueOrdersEXECUTE ProductName [ ; number ][[, n][ OUTPUT ]]Modify stored Procedures Syntax:ALTER PROCEDURE procedure_name[WITH option]ASsql_statement [...n]Modify stored Procedures Example:ALTER PROC dbo.overdueOrdersASSELECT CONVERT(CHAR(8), RequiredDate,1) RequiredDate, CONVERT(CHAR(8), orderDate,1) orderDate, orderId, Customerid, EmployeeIDFROM dbo.ordersWHERE RequiredDate [ [,] ...n] ] [AS ]BEGIN function_body RETURN scalar_expressionEND

FUNCTIONExample: CREATE FUNCTION dbo.OrderNum (@monthOrd tinyint ) RETURNS tinyintAS BEGIN DECLARE @Ordnum tinyintSELECT @Ordnum = count(orderid)FROM OrdersWHERE month(orderdate)= @monthOrdRETURN @OrdnumENDGOFUNCTIONExecute: SELECT dbo.OrderNum(7)Function can be used in the Where clauseSelect orderid from orders where dbo.OrderNum(7) > 50 and month(orderdate)=7

FUNCTIONTable-valued Functions

CREATE FUNCTION [ owner_name. ] function_name ([{ @parameter_name [AS] scalar_parameter_data_type [= default ] } [,...n ] ]) RETURNS TABLE [WITH < function_option > [ [,] ...n ] ] [AS ] RETURN [(] select-stmt [)]

Mt hm inline table-valued: N c th c xem nh l mt View c tham s. Chng thc thi mt cu lnh Select nh trong mt view nhng c th bao gm cc tham s, ging nh th tc.

27FUNCTIONExample: CREATE FUNCTION SalesByCategory(@Categoryid Int)RETURNS TABLEASRETURN (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)

FUNCTIONMultistatement Table-valuesd CREATE FUNCTION [owner_name.]function_name([{@parameter_name [AS] data_type [=default]} [ ,n ]])RETURNS @return_variableTABLE ({column_definition | table_constraint} [ ,n ])[WITH { ENCRYPTION | SCHEMABINDING } [ [,] ...n] ][AS]BEGINfunction_bodyRETURNENDFUNCTIONExample: CREATE FUNCTION Contacts(@suppliers bit=0)RETURNS @Contacts TABLE (ContactName nvarchar(30), Phone nvarchar(24), ContactType nvarchar(15))ASBEGININSERT @ContactsSELECT ContactName, Phone, 'Customer' FROM CustomersINSERT @ContactsSELECT FirstName + ' ' + LastName, HomePhone, 'Employee'FROM EmployeesIF @Suppliers=1INSERT @Contacts SELECT ContactName, Phone, 'SupplierFROM SuppliersRETURNEND

FUNCTIONExecute:SELECT * FROM CONTACTS(1) ORDER BY ContactName