SlideShare uma empresa Scribd logo
1 de 19
Stored Procedures
CIS-182
BATCH
• Batch is a logical group of SQL statements
– Run-time error will halt execution only of FURTHER
steps
– Can break up work
• Stored procedures
• User-defined functions
• Views
Scripts v. Stored Procedures
• Script: Text file of SQL commands
• Stored Procedure: SQL commands stored in
database itself
– SPROC’s have more capabilities than a script
Format of SPROC’s
CREATE PROC <name>
<parameter list>
AS
<instructions to execute>
EXECUTE
• EXEC(cute) statement
OR
• EXEC(cute) stored procedure name
• Statement or sproc runs in it’s own scope
– Can’t ‘share’ variables directly
– User’s security rules apply
– Can’t be used in User Defined Function (UDF)
Uses of Stored Procedures
• For returning data
• For editing data
• For calculations
Parameters
• Method for sending data into and from a stored
procedure
– INPUT parameters are values sent in
– OUTPUT parameters are values returned
• Must have a holding space (variable) for the returned data
• Defined before start of procedure (AS)
Declaring Parameters
• Include name and datatype
• Default value is optional
– Without a default value, parameter is required
• Direction is optional (input is default)
– An output parameter must have direction specified
Sample Input Parameter
CREATE PROC upFindStudent
@SID char(9)
AS
SELECT *
FROM Students_T
Where SchoolID=@SID
Sample Output Parameter
CREATE PROC upFindStudentID
@First varchar(25),
@Last varchar(35),
@SID char(9) OUTPUT
AS
SELECT @SID=SchoolID
FROM Students_T
Where @First=Firstname and
@Last=Lastname
Variables
• Create using DECLARE
• Need to start with ‘@’
• Can use SQL data types or custom data types
DECLARE @StudentName varchar(50)
Variable Assignment
• SET is usually used similar to procedural
language
SET @Var=value
• SELECT is usually used when getting a value
from a query
SELECT @Var=Sum(PossiblePoints) FROM
Assignments
Return Values
• Result of stored procedure indicates success or
failure
• Non-zero value indicates a problem
• Must be an integer
• Different from an output parameter
– Output parameter is about data
• RETURN <value>
– Causes immediate exit
Decision-making
• IF … ELSE
– No end if
– Need to use Begin/End if have more than one
instruction to execute
IF StartDate < EndDate
Begin
…
End
ELSE
Simple Case Statement
• CASE
– Similar to SELECT CASE or SWITCH
– Compares one value to different cases
CASE Category
WHEN ‘pop_comp’ THEN ‘Popular Computing’
WHEN ‘mod_cook’ THEN ‘Modern Cooking’
END
Searched CASE
• No test expression
• Each WHEN has a boolean test
CASE
WHEN Points >= 90 THEN ‘A’
WHEN Points < 90 AND Extra > 0
THEN ‘A’
END
@@Error –
System Variable
• Determined after each SQL statement;
• 0 means statement was successful
• Number other than zero is typically a specific
error
• Can store value in variable and test
@@Identity –
System Variable
• Returns the last identity value used as a result of
INSERT or SELECT INTO
• Returns Null if operation failed or a value
wasn’t generated
• Returns last number created if multiple inserts
occur (i.e. SELECT INTO)
@@Rowcount –
System Variables
• Number of rows returned or affected by the last
statement
• 0 (zero) is often used as a logical test
– If no records found for where clause, notify system or
process

Mais conteúdo relacionado

Mais procurados

10g plsql slide
10g plsql slide10g plsql slide
10g plsql slide
Tanu_Manu
 

Mais procurados (19)

XML
XMLXML
XML
 
Mule data weave_4
Mule data weave_4Mule data weave_4
Mule data weave_4
 
Reactjs workshop
Reactjs workshopReactjs workshop
Reactjs workshop
 
CIS 282 Final Review
CIS 282 Final ReviewCIS 282 Final Review
CIS 282 Final Review
 
SQL Intro
SQL IntroSQL Intro
SQL Intro
 
Oracle PL/SQL Best Practices
Oracle PL/SQL Best PracticesOracle PL/SQL Best Practices
Oracle PL/SQL Best Practices
 
Analytical Functions for DWH
Analytical Functions for DWHAnalytical Functions for DWH
Analytical Functions for DWH
 
Presto Functions
Presto FunctionsPresto Functions
Presto Functions
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 6...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 6... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 6...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 6...
 
High Performance Plsql
High Performance PlsqlHigh Performance Plsql
High Performance Plsql
 
iOS Beginners Lesson 1
iOS Beginners Lesson 1iOS Beginners Lesson 1
iOS Beginners Lesson 1
 
Jumping Into Java Then!
Jumping Into Java Then!Jumping Into Java Then!
Jumping Into Java Then!
 
Web Service Workshop - 3 days
Web Service Workshop - 3 daysWeb Service Workshop - 3 days
Web Service Workshop - 3 days
 
Coding standards
Coding standards Coding standards
Coding standards
 
C# advanced topics and future - C#5
C# advanced topics and future - C#5C# advanced topics and future - C#5
C# advanced topics and future - C#5
 
Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQL
 
Dynamic Publishing with Arbortext Data Merge
Dynamic Publishing with Arbortext Data MergeDynamic Publishing with Arbortext Data Merge
Dynamic Publishing with Arbortext Data Merge
 
10g plsql slide
10g plsql slide10g plsql slide
10g plsql slide
 
Do IT with SQL
Do IT with SQLDo IT with SQL
Do IT with SQL
 

Semelhante a Stored procedures

Intro to tsql unit 14
Intro to tsql   unit 14Intro to tsql   unit 14
Intro to tsql unit 14
Syed Asrarali
 
Agile db testing_techniques
Agile db testing_techniquesAgile db testing_techniques
Agile db testing_techniques
Tarik Essawi
 
Empower my sql server administration with 5.7 instruments
Empower my sql server administration with 5.7 instrumentsEmpower my sql server administration with 5.7 instruments
Empower my sql server administration with 5.7 instruments
Marco Tusa
 

Semelhante a Stored procedures (20)

Intro to tsql unit 14
Intro to tsql   unit 14Intro to tsql   unit 14
Intro to tsql unit 14
 
Intro to tsql
Intro to tsqlIntro to tsql
Intro to tsql
 
5. stored procedure and functions
5. stored procedure and functions5. stored procedure and functions
5. stored procedure and functions
 
Stored procedures
Stored proceduresStored procedures
Stored procedures
 
Stored procedures
Stored proceduresStored procedures
Stored procedures
 
Store programs
Store programsStore programs
Store programs
 
Agile db testing_techniques
Agile db testing_techniquesAgile db testing_techniques
Agile db testing_techniques
 
Empower my sql server administration with 5.7 instruments
Empower my sql server administration with 5.7 instrumentsEmpower my sql server administration with 5.7 instruments
Empower my sql server administration with 5.7 instruments
 
New T-SQL Features in SQL Server 2012
New T-SQL Features in SQL Server 2012 New T-SQL Features in SQL Server 2012
New T-SQL Features in SQL Server 2012
 
Informatica overview
Informatica overviewInformatica overview
Informatica overview
 
Informatica overview
Informatica overviewInformatica overview
Informatica overview
 
SQL Server Stored procedures
SQL Server Stored proceduresSQL Server Stored procedures
SQL Server Stored procedures
 
An Approach to Sql tuning - Part 1
An Approach to Sql tuning - Part 1An Approach to Sql tuning - Part 1
An Approach to Sql tuning - Part 1
 
Pl sql
Pl sqlPl sql
Pl sql
 
PL/SQL Tips and Techniques Webinar Presentation
PL/SQL Tips and Techniques Webinar PresentationPL/SQL Tips and Techniques Webinar Presentation
PL/SQL Tips and Techniques Webinar Presentation
 
Procedures/functions of rdbms
Procedures/functions of rdbmsProcedures/functions of rdbms
Procedures/functions of rdbms
 
Performance Schema for MySQL Troubleshooting
Performance Schema for MySQL TroubleshootingPerformance Schema for MySQL Troubleshooting
Performance Schema for MySQL Troubleshooting
 
Dreamforce Campfire - Apex Testing Tips and Tricks
Dreamforce Campfire - Apex Testing Tips and TricksDreamforce Campfire - Apex Testing Tips and Tricks
Dreamforce Campfire - Apex Testing Tips and Tricks
 
Performance Tuning with Execution Plans
Performance Tuning with Execution PlansPerformance Tuning with Execution Plans
Performance Tuning with Execution Plans
 
PL/SQL Fundamentals I
PL/SQL Fundamentals IPL/SQL Fundamentals I
PL/SQL Fundamentals I
 

Mais de Randy Riness @ South Puget Sound Community College

Mais de Randy Riness @ South Puget Sound Community College (20)

Normalization
NormalizationNormalization
Normalization
 
CIS160 final review
CIS160 final reviewCIS160 final review
CIS160 final review
 
SQL Constraints
SQL ConstraintsSQL Constraints
SQL Constraints
 
CIS 245 Final Review
CIS 245 Final ReviewCIS 245 Final Review
CIS 245 Final Review
 
CIS145 Final Review
CIS145 Final ReviewCIS145 Final Review
CIS145 Final Review
 
Cis166 Final Review C#
Cis166 Final Review C#Cis166 Final Review C#
Cis166 Final Review C#
 
Classes and Objects
Classes and ObjectsClasses and Objects
Classes and Objects
 
CIS245 sql
CIS245 sqlCIS245 sql
CIS245 sql
 
Cis245 Midterm Review
Cis245 Midterm ReviewCis245 Midterm Review
Cis245 Midterm Review
 
CSS
CSSCSS
CSS
 
XPath
XPathXPath
XPath
 
XSLT Overview
XSLT OverviewXSLT Overview
XSLT Overview
 
Views
ViewsViews
Views
 
CIS282 Midterm review
CIS282 Midterm reviewCIS282 Midterm review
CIS282 Midterm review
 
Schemas 2 - Restricting Values
Schemas 2 - Restricting ValuesSchemas 2 - Restricting Values
Schemas 2 - Restricting Values
 
CIS 145 test 1 review
CIS 145 test 1 reviewCIS 145 test 1 review
CIS 145 test 1 review
 
XML schemas
XML schemasXML schemas
XML schemas
 
Document type definitions part 2
Document type definitions part 2Document type definitions part 2
Document type definitions part 2
 
Document type definitions part 1
Document type definitions part 1Document type definitions part 1
Document type definitions part 1
 
DOM specifics
DOM specificsDOM specifics
DOM specifics
 

Último

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Último (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 

Stored procedures

  • 2. BATCH • Batch is a logical group of SQL statements – Run-time error will halt execution only of FURTHER steps – Can break up work • Stored procedures • User-defined functions • Views
  • 3. Scripts v. Stored Procedures • Script: Text file of SQL commands • Stored Procedure: SQL commands stored in database itself – SPROC’s have more capabilities than a script
  • 4. Format of SPROC’s CREATE PROC <name> <parameter list> AS <instructions to execute>
  • 5. EXECUTE • EXEC(cute) statement OR • EXEC(cute) stored procedure name • Statement or sproc runs in it’s own scope – Can’t ‘share’ variables directly – User’s security rules apply – Can’t be used in User Defined Function (UDF)
  • 6. Uses of Stored Procedures • For returning data • For editing data • For calculations
  • 7. Parameters • Method for sending data into and from a stored procedure – INPUT parameters are values sent in – OUTPUT parameters are values returned • Must have a holding space (variable) for the returned data • Defined before start of procedure (AS)
  • 8. Declaring Parameters • Include name and datatype • Default value is optional – Without a default value, parameter is required • Direction is optional (input is default) – An output parameter must have direction specified
  • 9. Sample Input Parameter CREATE PROC upFindStudent @SID char(9) AS SELECT * FROM Students_T Where SchoolID=@SID
  • 10. Sample Output Parameter CREATE PROC upFindStudentID @First varchar(25), @Last varchar(35), @SID char(9) OUTPUT AS SELECT @SID=SchoolID FROM Students_T Where @First=Firstname and @Last=Lastname
  • 11. Variables • Create using DECLARE • Need to start with ‘@’ • Can use SQL data types or custom data types DECLARE @StudentName varchar(50)
  • 12. Variable Assignment • SET is usually used similar to procedural language SET @Var=value • SELECT is usually used when getting a value from a query SELECT @Var=Sum(PossiblePoints) FROM Assignments
  • 13. Return Values • Result of stored procedure indicates success or failure • Non-zero value indicates a problem • Must be an integer • Different from an output parameter – Output parameter is about data • RETURN <value> – Causes immediate exit
  • 14. Decision-making • IF … ELSE – No end if – Need to use Begin/End if have more than one instruction to execute IF StartDate < EndDate Begin … End ELSE
  • 15. Simple Case Statement • CASE – Similar to SELECT CASE or SWITCH – Compares one value to different cases CASE Category WHEN ‘pop_comp’ THEN ‘Popular Computing’ WHEN ‘mod_cook’ THEN ‘Modern Cooking’ END
  • 16. Searched CASE • No test expression • Each WHEN has a boolean test CASE WHEN Points >= 90 THEN ‘A’ WHEN Points < 90 AND Extra > 0 THEN ‘A’ END
  • 17. @@Error – System Variable • Determined after each SQL statement; • 0 means statement was successful • Number other than zero is typically a specific error • Can store value in variable and test
  • 18. @@Identity – System Variable • Returns the last identity value used as a result of INSERT or SELECT INTO • Returns Null if operation failed or a value wasn’t generated • Returns last number created if multiple inserts occur (i.e. SELECT INTO)
  • 19. @@Rowcount – System Variables • Number of rows returned or affected by the last statement • 0 (zero) is often used as a logical test – If no records found for where clause, notify system or process