22
Introduction to Stored Procedure & Functions Module 4

Module04

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: Module04

Introduction to Stored Procedure & Functions

Module 4

Page 2: Module04

• Branching Controls• Transactions• Stored Procedures

– Benefits– Rules– Types of Stored Procedure– Types of Parameter– Executing Stored Procedure– Working with stored procedure– Delete Stored Procedure

• User Defined Functions

Learning Objectives

Page 3: Module04

At the end of this section, you should be able to work with:

• Branching Controls• Transactions Blocks• Stored Procedures• Functions

Module 4 : Agenda

Page 4: Module04

• Conditions – If Conditions

– Case Expression

• Declare• Begin…End

Control Flow Language

Page 5: Module04

Control Flow Language

• Conditions – If…else

Syntax :

Example:

If <Boolean_expression>

Statements to be executed

else

Statements to be executed

IF EXISTS(SELECT zip

FROM authors

WHERE zip='9470')

PRINT 'Msg print‘

ELSE

PRINT 'Msg print else'

Page 6: Module04

• Conditions – Case Expression

Syntax :

Example:

Control Flow Language

case <expression>

when <value1> then <result1>

when <valuen> then <resultn>

else <result>

End

SELECT CASE convert(int, (RAND() * 3))

WHEN 0 THEN ‘A’

WHEN 1 THEN ‘B’

ELSE ‘E’

END

Page 7: Module04

• Declare is used to define local variables

• Variable declaration is always prefixed with an ‘@’ symbol

Example:

Control Flow Language – Local Variable declaration

DECLARE @mytab int

SET @mytab=1

SELECT @mytab

Page 8: Module04

• The begin and end keywords create a block for a series of statements enclosed in it.

• In the following example, the if condition would be applicable to all the statements in the begin and end block.

• begin…end blocks can be nested.

example:

Control Flow Language – Blocks

IF(SELECT sum(price)

FROM titles) < 200

BEGIN

UPDATE titles

SET price = price * 2

SELECT title, price

FROM titles

WHERE price > 200

END

Page 9: Module04

What is a Transaction?

• A transaction usually means a sequence of information exchange and related work (such as database updating) that is treated as a unit for the purposes of satisfying a request and for ensuring database integrity

• For a transaction to be completed and database changes to be made permanent, a transaction has to be completed in its entirety. A program that manages or oversees the sequence of events that are part of a transaction is sometimes called a transaction monitor

• Transactions are supported by SQL. When a transaction completes successfully, database changes are said to be committed; when a transaction does not complete, changes are rolled back

Page 10: Module04

Transaction Control

• Transaction Control Statements– COMMIT

– ROLLBACK

Page 11: Module04

COMMIT

• Use the COMMIT statement to end your current transaction and make permanent all changes performed in the transaction

• If you do not explicitly commit the transaction and the program terminates abnormally, then the last uncommitted transaction is automatically rolled back

• SYNTAX:

COMMIT

Page 12: Module04

ROLLBACK

• Use the ROLLBACK statement to undo work done in the current transaction, or to manually undo the work done by an in-doubt distributed transaction

• SYNTAX:

ROLLBACK

Page 13: Module04

Transaction Example

BEGIN TRAN INSERT INTO EMPLOYEE

(EmpId, Fname, Lname, JobId, JobLvl) VALUES ( 'HUS42628M', 'ROGER', 'SLATE‘,12, 25)IF(@@ERROR <> 0) ROLLBACK TRAN

ELSE BEGIN DELETE FROM Jobs WHERE jobId =13

IF(@@ERROR <> 0) BEGIN PRINT 'Record not inserted in to Employee' ROLLBACK TRAN END ELSE BEGIN PRINT 'TRANSACTION SUCCESSFUL' COMMIT TRAN

END END

Page 14: Module04

BuiltIn Variables

Variable Description

@@ERROR Returns the error number for the last Transact-SQL statement executed.

@@IDENTITY Returns the last-inserted identity value.

@@ROWCOUNT Returns the number of rows affected by the last statement.

@@SERVERNAME Returns the name of the local server running Microsoft® SQL Server™.

@@LANGUAGE Returns the name of the language currently in use.

@@MAXCONNECTION

Returns the maximum number of simultaneous user connections allowed on a Microsoft® SQL Server™. The number returned is not necessarily the number currently configured.

Page 15: Module04

What is a Stored Procedure?

• A Stored procedure is a precompiled collection of Transact-SQL statements stored under a name and processed as a unit.

• SQL Server supplies stored procedures for managing SQL Server and displaying information about databases and users.

• SQL Server-supplied stored procedures are called system stored procedures.

Page 16: Module04

Stored Procedures (Continued)

• A stored procedure in SQL Server is similar to a procedure in other programming languages:– Can accept input parameters and return multiple values in the form of

output parameters to the calling procedure or batch– Can contain programming statements that perform operations in the

database, including calling other procedures– Can return a status value to a calling procedure or batch to indicate

success or failure (and the reason for failure)

Note : A stored procedure is different from a function– It do not return values in place of their names– It cannot be used directly in an expression

Page 17: Module04

Benefits of Stored Procedures

• Modular programming

• Faster execution

• Reduction in network traffic

• Can be used as a security mechanism

Page 18: Module04

Stored Procedures

CREATE PROC [ EDURE ] procedure_name [ ; number ]      [ { @parameter data_type }          [ VARYING ] [ = default ] [ OUTPUT ]

] [ ,...n ] [ WITH     { RECOMPILE | ENCRYPTION | RECOMPILE , ENCRYPTION } ] [ FOR REPLICATION ]

AS sql_statement [ ...n ]

procedure_name is the name of the of the procedure

@parameter parameter passed to the procedure

data_type type of data passed to the procedure

Page 19: Module04

Stored Procedure Example

CREATE PROCEDURE spAuthorDetail @AuthId int

AS BEGIN

SELECT AuthorLName, AuthorFName,

FROM Authors INNER JOIN TitleON Authors.AuthorId = Title.AuthorId WHERE Authors.AuthorId = @AuthId

ENDGO

• To execute a stored procedure use the execute command

Syntax : execute sp_name parameter1,parameter2……

e.g. execute spAuthorDetail 4563

Page 20: Module04

User Defined FunctionsCREATE FUNCTION Addition(@Number1 Decimal(6,2),

@Number2 Decimal(6,2))RETURNS Decimal(6,2)BEGIN DECLARE @Result Decimal(6,2) SET @Result = @Number1 + @Number2 RETURN @ResultEND;GO

• To execute this functionSELECT dbo.addition(2,2)

Page 21: Module04

Key Points

• SQL is an industry standard language for updating to, and getting information from, a database.

• Transaction management is implemented in SQL using COMMIT and ROLLBACK.

• Stored Procedures are precompiled collections of Transact-SQL statements stored under a name and processed as a unit.

Page 22: Module04

Questions & Comments