SlideShare a Scribd company logo
Introduction to Stored Procedure & Functions  Module 4
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
At the end of this section, you should be able to work with: Branching Controls Transactions Blocks Stored Procedures Functions Module 4 : Agenda
Conditions  If Conditions Case Expression Declare Begin…End Control Flow Language
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'
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
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
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
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
Transaction Control Transaction Control Statements COMMIT  ROLLBACK
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
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
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
BuiltIn Variables Returns the maximum number of simultaneous user connections allowed on a Microsoft® SQL Server™. The number returned is not necessarily the number currently configured. @@MAXCONNECTION Returns the name of the language currently in use. @@LANGUAGE Returns the name of the local server running Microsoft® SQL Server™. @@SERVERNAME Returns the number of rows affected by the last statement.  @@ROWCOUNT Returns the last-inserted identity value. @@IDENTITY Returns the error number for the last Transact-SQL statement executed. @@ERROR Description Variable
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.
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
Benefits of Stored Procedures Modular programming Faster execution Reduction in network traffic Can be used as a security mechanism
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
Stored Procedure Example To execute a stored procedure use the  execute  command  Syntax :  execute sp_name parameter1,parameter2…… e.g.  execute spAuthorDetail   4563 CREATE PROCEDURE spAuthorDetail   @AuthId  int AS  BEGIN SELECT AuthorLName,    AuthorFName, FROM Authors INNER JOIN Title ON Authors.AuthorId = Title.AuthorId  WHERE Authors.AuthorId = @AuthId  END GO
User Defined Functions To execute this function CREATE 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 @Result END; GO SELECT dbo.addition(2,2)
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.
Questions & Comments
Ad

More Related Content

What's hot (19)

Packages - PL/SQL
Packages - PL/SQLPackages - PL/SQL
Packages - PL/SQL
Esmita Gupta
 
Intro to tsql unit 15
Intro to tsql   unit 15Intro to tsql   unit 15
Intro to tsql unit 15
Syed Asrarali
 
PL/SQL
PL/SQLPL/SQL
PL/SQL
Vaibhav0
 
Oracle - Program with PL/SQL - Lession 17
Oracle - Program with PL/SQL - Lession 17Oracle - Program with PL/SQL - Lession 17
Oracle - Program with PL/SQL - Lession 17
Thuan Nguyen
 
Procedure n functions
Procedure n functionsProcedure n functions
Procedure n functions
Khadija Parween
 
Programming in Oracle with PL/SQL
Programming in Oracle with PL/SQLProgramming in Oracle with PL/SQL
Programming in Oracle with PL/SQL
lubna19
 
Oracle - Program with PL/SQL - Lession 01
Oracle - Program with PL/SQL - Lession 01Oracle - Program with PL/SQL - Lession 01
Oracle - Program with PL/SQL - Lession 01
Thuan Nguyen
 
Oracle - Program with PL/SQL - Lession 11
Oracle - Program with PL/SQL - Lession 11Oracle - Program with PL/SQL - Lession 11
Oracle - Program with PL/SQL - Lession 11
Thuan Nguyen
 
PL/SQL TRIGGERS
PL/SQL TRIGGERSPL/SQL TRIGGERS
PL/SQL TRIGGERS
Lakshman Basnet
 
Sql storeprocedure
Sql storeprocedureSql storeprocedure
Sql storeprocedure
ftz 420
 
Function and types
Function  and typesFunction  and types
Function and types
Sherin Fathima
 
Function
FunctionFunction
Function
Sherin Fathima
 
Store procedures
Store proceduresStore procedures
Store procedures
Farzan Wadood
 
Oracle PL sql 3
Oracle PL sql 3Oracle PL sql 3
Oracle PL sql 3
Sergio Ronchi
 
Functions
FunctionsFunctions
Functions
biplob04
 
Oracle - Program with PL/SQL - Lession 09
Oracle - Program with PL/SQL - Lession 09Oracle - Program with PL/SQL - Lession 09
Oracle - Program with PL/SQL - Lession 09
Thuan Nguyen
 
Intro to tsql
Intro to tsqlIntro to tsql
Intro to tsql
Syed Asrarali
 
Stored-Procedures-Presentation
Stored-Procedures-PresentationStored-Procedures-Presentation
Stored-Procedures-Presentation
Chuck Walker
 
Sql Functions And Procedures
Sql Functions And ProceduresSql Functions And Procedures
Sql Functions And Procedures
DataminingTools Inc
 
Intro to tsql unit 15
Intro to tsql   unit 15Intro to tsql   unit 15
Intro to tsql unit 15
Syed Asrarali
 
Oracle - Program with PL/SQL - Lession 17
Oracle - Program with PL/SQL - Lession 17Oracle - Program with PL/SQL - Lession 17
Oracle - Program with PL/SQL - Lession 17
Thuan Nguyen
 
Programming in Oracle with PL/SQL
Programming in Oracle with PL/SQLProgramming in Oracle with PL/SQL
Programming in Oracle with PL/SQL
lubna19
 
Oracle - Program with PL/SQL - Lession 01
Oracle - Program with PL/SQL - Lession 01Oracle - Program with PL/SQL - Lession 01
Oracle - Program with PL/SQL - Lession 01
Thuan Nguyen
 
Oracle - Program with PL/SQL - Lession 11
Oracle - Program with PL/SQL - Lession 11Oracle - Program with PL/SQL - Lession 11
Oracle - Program with PL/SQL - Lession 11
Thuan Nguyen
 
Sql storeprocedure
Sql storeprocedureSql storeprocedure
Sql storeprocedure
ftz 420
 
Oracle - Program with PL/SQL - Lession 09
Oracle - Program with PL/SQL - Lession 09Oracle - Program with PL/SQL - Lession 09
Oracle - Program with PL/SQL - Lession 09
Thuan Nguyen
 
Stored-Procedures-Presentation
Stored-Procedures-PresentationStored-Procedures-Presentation
Stored-Procedures-Presentation
Chuck Walker
 

Viewers also liked (20)

High Performance Front-End Development
High Performance Front-End DevelopmentHigh Performance Front-End Development
High Performance Front-End Development
drywallbmb
 
Multidimensional model programming
Multidimensional model programmingMultidimensional model programming
Multidimensional model programming
Steve Xu
 
Spatialware_2_Sql08
Spatialware_2_Sql08Spatialware_2_Sql08
Spatialware_2_Sql08
Mike Osbourn
 
Module06
Module06Module06
Module06
Sridhar P
 
Transact sql data definition language - ddl- reference
Transact sql data definition language - ddl- referenceTransact sql data definition language - ddl- reference
Transact sql data definition language - ddl- reference
Steve Xu
 
SQL Server 2008 for .NET Developers
SQL Server 2008 for .NET DevelopersSQL Server 2008 for .NET Developers
SQL Server 2008 for .NET Developers
llangit
 
Module07
Module07Module07
Module07
Sridhar P
 
Multi-thematic spatial databases
Multi-thematic spatial databasesMulti-thematic spatial databases
Multi-thematic spatial databases
Conor Mc Elhinney
 
Module01
Module01Module01
Module01
Sridhar P
 
Sql server ___________session3-normailzation
Sql server  ___________session3-normailzationSql server  ___________session3-normailzation
Sql server ___________session3-normailzation
Ehtisham Ali
 
Alasql - база данных SQL на JavaScript (MoscowJS)
Alasql - база данных SQL на JavaScript (MoscowJS)Alasql - база данных SQL на JavaScript (MoscowJS)
Alasql - база данных SQL на JavaScript (MoscowJS)
Andrey Gershun
 
X query language reference
X query language referenceX query language reference
X query language reference
Steve Xu
 
Css introduction
Css introductionCss introduction
Css introduction
Sridhar P
 
AlaSQL библиотека для обработки JavaScript данных (презентация для ForntEnd 2...
AlaSQL библиотека для обработки JavaScript данных (презентация для ForntEnd 2...AlaSQL библиотека для обработки JavaScript данных (презентация для ForntEnd 2...
AlaSQL библиотека для обработки JavaScript данных (презентация для ForntEnd 2...
Andrey Gershun
 
5 tsssisu sql_server_2012
5 tsssisu sql_server_20125 tsssisu sql_server_2012
5 tsssisu sql_server_2012
Steve Xu
 
SQL Server 2008 for Developers
SQL Server 2008 for DevelopersSQL Server 2008 for Developers
SQL Server 2008 for Developers
llangit
 
SQL Server 2008 Spatial Data - Getting Started
SQL Server 2008 Spatial Data - Getting StartedSQL Server 2008 Spatial Data - Getting Started
SQL Server 2008 Spatial Data - Getting Started
Integrated Network Strategies
 
Module05
Module05Module05
Module05
Sridhar P
 
Module02
Module02Module02
Module02
Sridhar P
 
Sql Server Data Tools - Codenamed JUNEAU
Sql Server Data Tools - Codenamed JUNEAUSql Server Data Tools - Codenamed JUNEAU
Sql Server Data Tools - Codenamed JUNEAU
Lohith Goudagere Nagaraj
 
High Performance Front-End Development
High Performance Front-End DevelopmentHigh Performance Front-End Development
High Performance Front-End Development
drywallbmb
 
Multidimensional model programming
Multidimensional model programmingMultidimensional model programming
Multidimensional model programming
Steve Xu
 
Spatialware_2_Sql08
Spatialware_2_Sql08Spatialware_2_Sql08
Spatialware_2_Sql08
Mike Osbourn
 
Transact sql data definition language - ddl- reference
Transact sql data definition language - ddl- referenceTransact sql data definition language - ddl- reference
Transact sql data definition language - ddl- reference
Steve Xu
 
SQL Server 2008 for .NET Developers
SQL Server 2008 for .NET DevelopersSQL Server 2008 for .NET Developers
SQL Server 2008 for .NET Developers
llangit
 
Multi-thematic spatial databases
Multi-thematic spatial databasesMulti-thematic spatial databases
Multi-thematic spatial databases
Conor Mc Elhinney
 
Sql server ___________session3-normailzation
Sql server  ___________session3-normailzationSql server  ___________session3-normailzation
Sql server ___________session3-normailzation
Ehtisham Ali
 
Alasql - база данных SQL на JavaScript (MoscowJS)
Alasql - база данных SQL на JavaScript (MoscowJS)Alasql - база данных SQL на JavaScript (MoscowJS)
Alasql - база данных SQL на JavaScript (MoscowJS)
Andrey Gershun
 
X query language reference
X query language referenceX query language reference
X query language reference
Steve Xu
 
Css introduction
Css introductionCss introduction
Css introduction
Sridhar P
 
AlaSQL библиотека для обработки JavaScript данных (презентация для ForntEnd 2...
AlaSQL библиотека для обработки JavaScript данных (презентация для ForntEnd 2...AlaSQL библиотека для обработки JavaScript данных (презентация для ForntEnd 2...
AlaSQL библиотека для обработки JavaScript данных (презентация для ForntEnd 2...
Andrey Gershun
 
5 tsssisu sql_server_2012
5 tsssisu sql_server_20125 tsssisu sql_server_2012
5 tsssisu sql_server_2012
Steve Xu
 
SQL Server 2008 for Developers
SQL Server 2008 for DevelopersSQL Server 2008 for Developers
SQL Server 2008 for Developers
llangit
 
Ad

Similar to Module04 (20)

Intro to tsql unit 14
Intro to tsql   unit 14Intro to tsql   unit 14
Intro to tsql unit 14
Syed Asrarali
 
Stored procedures
Stored proceduresStored procedures
Stored procedures
Prof.Nilesh Magar
 
Stored procedure,transaction
Stored procedure,transactionStored procedure,transaction
Stored procedure,transaction
baabtra.com - No. 1 supplier of quality freshers
 
Ruslan Platonov - Transactions
Ruslan Platonov - TransactionsRuslan Platonov - Transactions
Ruslan Platonov - Transactions
Dmitry Buzdin
 
PL/SQL Stored Procedures And Cursors.ppt
PL/SQL Stored Procedures And Cursors.pptPL/SQL Stored Procedures And Cursors.ppt
PL/SQL Stored Procedures And Cursors.ppt
sonaligaikwad281110
 
Mysqlppt
MysqlpptMysqlppt
Mysqlppt
Reka
 
Sql transacation
Sql transacationSql transacation
Sql transacation
baabtra.com - No. 1 supplier of quality freshers
 
Unit 3(rdbms)
Unit 3(rdbms)Unit 3(rdbms)
Unit 3(rdbms)
Jay Patel
 
Unit 3(rdbms)
Unit 3(rdbms)Unit 3(rdbms)
Unit 3(rdbms)
Jay Patel
 
Procedures/functions of rdbms
Procedures/functions of rdbmsProcedures/functions of rdbms
Procedures/functions of rdbms
jain.pralabh
 
PLSQL
PLSQLPLSQL
PLSQL
Shubham Bammi
 
Dynamic websites lec3
Dynamic websites lec3Dynamic websites lec3
Dynamic websites lec3
Belal Arfa
 
MS SQLSERVER:Sql Functions And Procedures
MS SQLSERVER:Sql Functions And ProceduresMS SQLSERVER:Sql Functions And Procedures
MS SQLSERVER:Sql Functions And Procedures
sqlserver content
 
MS SQL SERVER: Sql Functions And Procedures
MS SQL SERVER: Sql Functions And ProceduresMS SQL SERVER: Sql Functions And Procedures
MS SQL SERVER: Sql Functions And Procedures
sqlserver content
 
Lecture Notes Unit5 chapter17 Stored procedures and functions
Lecture Notes Unit5 chapter17 Stored procedures and functionsLecture Notes Unit5 chapter17 Stored procedures and functions
Lecture Notes Unit5 chapter17 Stored procedures and functions
Murugan146644
 
Oracle: Procedures
Oracle: ProceduresOracle: Procedures
Oracle: Procedures
oracle content
 
Tony jambu (obscure) tools of the trade for tuning oracle sq ls
Tony jambu   (obscure) tools of the trade for tuning oracle sq lsTony jambu   (obscure) tools of the trade for tuning oracle sq ls
Tony jambu (obscure) tools of the trade for tuning oracle sq ls
InSync Conference
 
SQl
SQlSQl
SQl
sarankumarv
 
SQL Server Stored procedures
SQL Server Stored proceduresSQL Server Stored procedures
SQL Server Stored procedures
Randy Riness @ South Puget Sound Community College
 
PLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrj
PLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrjPLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrj
PLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrj
KathanPatel49
 
Ad

Recently uploaded (20)

Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
Operations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdfOperations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdf
Arab Academy for Science, Technology and Maritime Transport
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
Political History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptxPolitical History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 

Module04

  • 1. Introduction to Stored Procedure & Functions Module 4
  • 2. 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
  • 3. At the end of this section, you should be able to work with: Branching Controls Transactions Blocks Stored Procedures Functions Module 4 : Agenda
  • 4. Conditions If Conditions Case Expression Declare Begin…End Control Flow Language
  • 5. 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'
  • 6. 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
  • 7. 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
  • 8. 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
  • 9. 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
  • 10. Transaction Control Transaction Control Statements COMMIT ROLLBACK
  • 11. 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
  • 12. 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
  • 13. 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
  • 14. BuiltIn Variables Returns the maximum number of simultaneous user connections allowed on a Microsoft® SQL Server™. The number returned is not necessarily the number currently configured. @@MAXCONNECTION Returns the name of the language currently in use. @@LANGUAGE Returns the name of the local server running Microsoft® SQL Server™. @@SERVERNAME Returns the number of rows affected by the last statement. @@ROWCOUNT Returns the last-inserted identity value. @@IDENTITY Returns the error number for the last Transact-SQL statement executed. @@ERROR Description Variable
  • 15. 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.
  • 16. 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
  • 17. Benefits of Stored Procedures Modular programming Faster execution Reduction in network traffic Can be used as a security mechanism
  • 18. 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
  • 19. Stored Procedure Example To execute a stored procedure use the execute command Syntax : execute sp_name parameter1,parameter2…… e.g. execute spAuthorDetail 4563 CREATE PROCEDURE spAuthorDetail @AuthId int AS BEGIN SELECT AuthorLName, AuthorFName, FROM Authors INNER JOIN Title ON Authors.AuthorId = Title.AuthorId WHERE Authors.AuthorId = @AuthId END GO
  • 20. User Defined Functions To execute this function CREATE 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 @Result END; GO SELECT dbo.addition(2,2)
  • 21. 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.

Editor's Notes

  • #5: Faculty Notes : if Defines conditional execution. … else Defines alternate execution when the if condition is false. case Defines conditional expressions using when…then statements instead of if…else. begin Beginning of a statement block. … end End of a statement block. while Repeat performance of statements while condition is true. break Exit from the end of the next outermost while loop. … continue Restart while loop. declare Declare local variables. goto label Go to label:, a position in a statement block. return Exit unconditionally. waitfor Set delay for command execution. print Print a user-defined message or local variable on user’s screen. raiserror Print a user-defined message or local variable on user’s screen and set a system flag in the global variable @@ error . /* comment */ or -- comment Insert a comment anywhere in a Transact-SQL statement.
  • #6: Faculty Notes: Example: if exists(select zip from authors where zip=&apos;9470&apos;) print &apos;Msg print&apos; else print &apos;Msg print else&apos;
  • #7: Faculty Notes : Example: select CASE convert(int, (RAND() * 3)) when 0 then &amp;quot;A&amp;quot; when 1 then &amp;quot;B&amp;quot; else &amp;quot;E&amp;quot; end
  • #9: Faculty Notes : The begin and end keywords create a block for a series of statements enclosed in it. This is treated as one unit by control of flow constructs. Enclosed statements in begin and end are called a statement block . The syntax of begin...end is: begin statement block end
  • #10: Faculty Notes: A typical transaction is a catalog merchandise order phoned in by a customer and entered into a computer by a customer representative. The order transaction involves checking an inventory database, confirming that the item is available, placing the order and confirming that the order has been placed and noting the expected time of shipment. If we view this as a single transaction, then all of the steps must be completed before the transaction is successful and the database is actually changed to reflect the new order. If something happens before the transaction is successfully completed, any changes to the database must be documented so that they can be undone. SQL Server transactions are often described as having the ACID properties or &amp;quot;passing the ACID test,&amp;quot; where ACID is an acronym for atomic, consistent, isolated, and durable. Transactional adherence to the ACID tenets is commonplace in modern RDBMS and is a prerequisite for ensuring the safety and reliability of data.
  • #11: Faculty Notes: Review points on slide
  • #12: Faculty Notes: Review points on slide
  • #13: Faculty Notes: Review points on slide
  • #14: Faculty Notes: We can begin a Transaction explicitly using keyword BEGIN TRANS and End Trans and add the statements to be executed. When this transition is executed if any of the statements fail the whole transaction will be rolled back In the Example two statements are executed one after another in a transaction The insert statement is executed and one row is inserted (But not yet committed its still in the Transaction) Assume the Delete Statement fails, as Job id 13 is in use in another child table. The @@ERROR variable checks if there’s any error for the transaction and if found rolls back the whole transaction as a whole i.e. It does not insert the record in the employee table
  • #15: Faculty Notes: These variables are provided by SQL Server. Explanation of each has been described above.
  • #16: Faculty Notes: Review points on slide
  • #17: Faculty Notes: Review points on slide
  • #18: Faculty Notes: Modular programming You can create the procedure once, store it in the database, and call it any number of times in your program. Stored procedures can be created by a person who specializes in database programming, and they can be modified independently of the program source code. Faster Execution If the operation requires a large amount of Transact-SQL code or is performed repetitively, stored procedures can be faster than batches of Transact-SQL code. They are parsed and optimized when they are created, and an in-memory version of the procedure can be used after the procedure is executed the first time. Transact-SQL statements repeatedly sent from the client each time they run, are compiled and optimized every time they are executed by SQL Server. Network traffic An operation requiring hundreds of lines of Transact-SQL code can be performed through a single statement that executes the code in a procedure, rather than by sending hundreds of lines of code over the network. Security Mechanism Users can be granted permission to execute a stored procedure even if they do not have permission to execute the procedure&apos;s statements directly.
  • #19: Faculty Notes: procedure_name Is the name of the new stored procedure. ; number Is an optional integer used to group procedures of the same name so they can be dropped together with a single DROP PROCEDURE statement. For example, the procedures used with an application called orders may be named orderproc ;1, orderproc ;2, and so on. @ parameter Is a parameter in the procedure. One or more parameters can be declared in a CREATE PROCEDURE statement. The value of each declared parameter must be supplied by the user when the procedure is executed (unless a default for the parameter is defined). Specify a parameter name using an at sign (@) as the first character. data_type Is the parameter data type. All data types, including text, ntext and image , can be used as a parameter for a stored procedure. Note   There is no limit on the maximum number of output parameters that can be of cursor data type. VARYING Specifies the result set supported as an output parameter (constructed dynamically by the stored procedure and whose contents can vary). Default Is a default value for the parameter. If a default is defined, the procedure can be executed without specifying a value for that parameter. n Is a placeholder indicating that a maximum of 2,100 parameters can be specified. {RECOMPILE | ENCRYPTION | RECOMPILE , ENCRYPTION} RECOMPILE indicates that SQL Server does not cache a plan for this procedure and the procedure is recompiled at run time. ENCRYPTION indicates that SQL Server encrypts the syscomments table entry containing the text of the CREATE PROCEDURE statement. FOR REPLICATION Specifies that stored procedures created for replication cannot be executed on the Subscriber. A stored procedure created with the FOR REPLICATION option is used as a stored procedure filter and only executed during replication. This option cannot be used with the WITH RECOMPILE option. AS Specifies the actions the procedure is to take. sql_statement Is any number and type of Transact-SQL statements to be included in the procedure. Some limitations apply. n Is a placeholder that indicates multiple Transact-SQL statements may be included in this procedure.
  • #20: Faculty Notes: The above example creates a stored procedure spAuthorDetail it accepts one parameter @AuthId of int data type when the sp is to be executed the user has to pass value to the stored procedure as shown below execute spAuthorDetail 1456 The values passed to the stored procedure are further passed to the select query. Based on the parameter passed the select statement is executed .
  • #21: Facutly notes: We can also use function to insert data into a table Insert into mytab values (dbo.addition(2,2))
  • #22: Faculty Notes: Review the key points on the slide. The key points should be used to summarize the content covered throughout this presentation.