SlideShare a Scribd company logo
Stored Procedures CIS-282
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
BATCH Batch is a logical group of SQL statements Run-time error will halt execution only of FURTHER steps Can break up multiple steps using GO Not available in all tools GO causes editing tool to send statements to that point for execution GO isn’t sent to SQL Server
Format of SPROC’s CREATE PROCEDURE <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 (select) 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
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
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
Decision Making SQL supports two structures for branching: IF CASE Both structures are similar to other languages (IF … THEN, SELECT CASE)  Both structures tend to have specific places where used
IF Blocks 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 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
Looping (While) Typically used with a CURSOR Cursor data type allows a table to be stored in memory and each row/field to be accessed BREAK allows early exit from loop CONTINUE forces control to start of loop Working with sets is preferred over loops (SQL is about sets)
Finding Identity Values When need to find the value used to identify the last row added @@Identity Scope_Identity Ident_Current
@@Identity –  System Variable Returns the last identity value used as a result of INSERT or SELECT INTO Not limited to current scope; may not get correct value Returns Null if operation failed or a value wasn’t generated Returns last number created if multiple inserts occur (i.e. SELECT INTO)
Scope_Identity() Return the last identity values generated in any table in the current session.  Returns values inserted only within the current scope Not affected by other operations.
Ident_Current() Not limited by scope and session; Limited to a specified table (table name specified as an argument value).
@@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
Errors Errors can occur because of SQL statement Invalid syntax, or data type Errors can also reflect business rules Data doesn’t match requirements
@@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
Try/Catch Similar to .Net languages Need to include BEGIN/END BEGIN TRY <code> END TRY BEGIN CATCH <error handling code> END CATCH
Raise Error Used to send information to calling program Syntax: RaisError (Message string OR Message ID, Severity, State) Severity – <14 information; 15-19 warning or user can correct; 20+ fatal State – way to differentiate problems if needed; typically use 1 RAISERROR (50001,16,1)
Error Message  Message ID or String Use ID if have custom or TSQL error to use Use String for ‘on the fly’ message Stored Error Messages are server-specific Can add message Number greater than 50000
Custom Error Messages Messages can include a parameter with % to allow addition to message ‘ D’ – signed integer ‘ O’ – unsigned octal ‘ P’ – pointer ‘ S’ – string ‘ U’ – unsigned integer ‘ X’ or ‘x’ – unsigned hexadecimal
Severity & State 1 – 18: Informational 11 – 16 typically raise error at client 19 – 25: Severe error 20+ is fatal error and connection will terminate State is ‘ad hoc’ and can help if same error happens in multiple places Range of 1 – 127
Sample Error Message RaisError(“Operation cannot be completed because field %s cannot be null”,1,1,”fieldname”)
Transactions Provides method for canceling an operation Can restore rows, columns to original state in event of error or business logic failure Use when changes will either be committed or discarded in entirety
ACID Atomicity : All of the changes will be accepted or none of the changes will be accepted Consistency : Data is either in its original or changed state Isolation : If multiple transactions occur, data is never available in an intermediate state Durability : Once finished, all changes are complete and changes can only be done by another transaction/unit of work
Using A Transaction Begin Tran: Identifies the start Commit Tran: Write changes Rollback Tran: Cancel changes Issue A Commit Or Rollback Or Connection Stays Open Until Terminated
Locking & Concurrency Locking allows a transaction to ensure that it can rollback Prevents other operations from changing that data Concurrency refers to multiple actions running against database at the same time What happens if you want to change data I’m working with?
Sample Locking Levels Database Table Extent (memory) Page (subset of extent) Key Row
Cursors Processing based on each row not set operations Declare @Cursor Cursor Set @Cursor = Cursor For (select statement) Open @Cursor Fetch Next From @Cursor into (variables matching field list in select)
Using a Cursor Declare @Students Cursor Set @Cursor = Cursor For (Select FirstName, LastName From Students) Open @Students While @@Fetch_Status = 0 Begin Fetch Next From @Students Into @First, @Last Print @First + ‘ ‘+ @Last  End Close @Students Deallocate @Students
@@Fetch_Status 0 success; -1 failed (read record outside recordset); -2 missing record (eg. someone else deleted)
Ad

More Related Content

What's hot (20)

Triggers and Stored Procedures
Triggers and Stored ProceduresTriggers and Stored Procedures
Triggers and Stored Procedures
Tharindu Weerasinghe
 
SQL Overview
SQL OverviewSQL Overview
SQL Overview
Stewart Rogers
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
baabtra.com - No. 1 supplier of quality freshers
 
SQL Tutorial - Basic Commands
SQL Tutorial - Basic CommandsSQL Tutorial - Basic Commands
SQL Tutorial - Basic Commands
1keydata
 
Integrity constraints in dbms
Integrity constraints in dbmsIntegrity constraints in dbms
Integrity constraints in dbms
Vignesh Saravanan
 
Introduction to database & sql
Introduction to database & sqlIntroduction to database & sql
Introduction to database & sql
zahid6
 
Query Optimization in SQL Server
Query Optimization in SQL ServerQuery Optimization in SQL Server
Query Optimization in SQL Server
Rajesh Gunasundaram
 
Stored-Procedures-Presentation
Stored-Procedures-PresentationStored-Procedures-Presentation
Stored-Procedures-Presentation
Chuck Walker
 
SQL Joins With Examples | Edureka
SQL Joins With Examples | EdurekaSQL Joins With Examples | Edureka
SQL Joins With Examples | Edureka
Edureka!
 
Packages in PL/SQL
Packages in PL/SQLPackages in PL/SQL
Packages in PL/SQL
Pooja Dixit
 
Sql and Sql commands
Sql and Sql commandsSql and Sql commands
Sql and Sql commands
Knowledge Center Computer
 
8. sql
8. sql8. sql
8. sql
khoahuy82
 
SQL
SQLSQL
SQL
Shunya Ram
 
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with ExamplesDML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
LGS, GBHS&IC, University Of South-Asia, TARA-Technologies
 
Chapter 3 stored procedures
Chapter 3 stored proceduresChapter 3 stored procedures
Chapter 3 stored procedures
baabtra.com - No. 1 supplier of quality freshers
 
Trigger
TriggerTrigger
Trigger
VForce Infotech
 
MYSQL-Database
MYSQL-DatabaseMYSQL-Database
MYSQL-Database
V.V.Vanniaperumal College for Women
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
Dhyey Dattani
 
Introduction of sql server indexing
Introduction of sql server indexingIntroduction of sql server indexing
Introduction of sql server indexing
Mahabubur Rahaman
 
Sql commands
Sql commandsSql commands
Sql commands
Balakumaran Arunachalam
 

Similar to SQL Server Stored procedures (20)

Stored procedures
Stored proceduresStored procedures
Stored procedures
Randy Riness @ South Puget Sound Community College
 
CIS 282 Final Review
CIS 282 Final ReviewCIS 282 Final Review
CIS 282 Final Review
Randy Riness @ South Puget Sound Community College
 
Intro to tsql unit 11
Intro to tsql   unit 11Intro to tsql   unit 11
Intro to tsql unit 11
Syed Asrarali
 
Intro to tsql unit 14
Intro to tsql   unit 14Intro to tsql   unit 14
Intro to tsql unit 14
Syed Asrarali
 
Intro to tsql
Intro to tsqlIntro to tsql
Intro to tsql
Syed Asrarali
 
Module04
Module04Module04
Module04
Sridhar P
 
Exception handling in SQL with Execution
Exception handling in SQL with ExecutionException handling in SQL with Execution
Exception handling in SQL with Execution
hragrawal20
 
CIS160 final review
CIS160 final reviewCIS160 final review
CIS160 final review
Randy Riness @ South Puget Sound Community College
 
PLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrj
PLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrjPLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrj
PLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrj
KathanPatel49
 
Database development coding standards
Database development coding standardsDatabase development coding standards
Database development coding standards
Alessandro Baratella
 
ADO.Net Improvements in .Net 2.0
ADO.Net Improvements in .Net 2.0ADO.Net Improvements in .Net 2.0
ADO.Net Improvements in .Net 2.0
David Truxall
 
Introduction To Programming
Introduction To ProgrammingIntroduction To Programming
Introduction To Programming
cwarren
 
Sql Server 2008 New Programmability Features
Sql Server 2008 New Programmability FeaturesSql Server 2008 New Programmability Features
Sql Server 2008 New Programmability Features
sqlserver.co.il
 
PLSQLmy Updated (1).pptx
PLSQLmy Updated (1).pptxPLSQLmy Updated (1).pptx
PLSQLmy Updated (1).pptx
vamsiyadav39
 
PLSQL
PLSQLPLSQL
PLSQL
Shubham Bammi
 
Data integrity
Data integrityData integrity
Data integrity
Urooj Sabar
 
Web Developement Workshop (Oct 2009) Slides
Web Developement Workshop (Oct 2009) SlidesWeb Developement Workshop (Oct 2009) Slides
Web Developement Workshop (Oct 2009) Slides
Manish Sinha
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
Information Technology
 
Procedures functions structures in VB.Net
Procedures  functions  structures in VB.NetProcedures  functions  structures in VB.Net
Procedures functions structures in VB.Net
tjunicornfx
 
Database programming
Database programmingDatabase programming
Database programming
Shree M.L.Kakadiya MCA mahila college, Amreli
 
Ad

More from Randy Riness @ South Puget Sound Community College (20)

Stored procedures
Stored proceduresStored procedures
Stored procedures
Randy Riness @ South Puget Sound Community College
 
3 sql overview
3 sql overview3 sql overview
3 sql overview
Randy Riness @ South Puget Sound Community College
 
Normalization
NormalizationNormalization
Normalization
Randy Riness @ South Puget Sound Community College
 
SQL Constraints
SQL ConstraintsSQL Constraints
SQL Constraints
Randy Riness @ South Puget Sound Community College
 
CIS 245 Final Review
CIS 245 Final ReviewCIS 245 Final Review
CIS 245 Final Review
Randy Riness @ South Puget Sound Community College
 
CIS145 Final Review
CIS145 Final ReviewCIS145 Final Review
CIS145 Final Review
Randy Riness @ South Puget Sound Community College
 
Cis166 Final Review C#
Cis166 Final Review C#Cis166 Final Review C#
Cis166 Final Review C#
Randy Riness @ South Puget Sound Community College
 
CIS245 sql
CIS245 sqlCIS245 sql
CIS245 sql
Randy Riness @ South Puget Sound Community College
 
Cis245 Midterm Review
Cis245 Midterm ReviewCis245 Midterm Review
Cis245 Midterm Review
Randy Riness @ South Puget Sound Community College
 
CSS
CSSCSS
CSS
Randy Riness @ South Puget Sound Community College
 
XPath
XPathXPath
XPath
Randy Riness @ South Puget Sound Community College
 
XSLT Overview
XSLT OverviewXSLT Overview
XSLT Overview
Randy Riness @ South Puget Sound Community College
 
Views
ViewsViews
Views
Randy Riness @ South Puget Sound Community College
 
CIS282 Midterm review
CIS282 Midterm reviewCIS282 Midterm review
CIS282 Midterm review
Randy Riness @ South Puget Sound Community College
 
Schemas 2 - Restricting Values
Schemas 2 - Restricting ValuesSchemas 2 - Restricting Values
Schemas 2 - Restricting Values
Randy Riness @ South Puget Sound Community College
 
CIS 145 test 1 review
CIS 145 test 1 reviewCIS 145 test 1 review
CIS 145 test 1 review
Randy Riness @ South Puget Sound Community College
 
XML schemas
XML schemasXML schemas
XML schemas
Randy Riness @ South Puget Sound Community College
 
Document type definitions part 2
Document type definitions part 2Document type definitions part 2
Document type definitions part 2
Randy Riness @ South Puget Sound Community College
 
Document type definitions part 1
Document type definitions part 1Document type definitions part 1
Document type definitions part 1
Randy Riness @ South Puget Sound Community College
 
Ad

Recently uploaded (20)

Module 1: Foundations of Research
Module 1: Foundations of ResearchModule 1: Foundations of Research
Module 1: Foundations of Research
drroxannekemp
 
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living WorkshopLDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDM Mia eStudios
 
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
Dr. Nasir Mustafa
 
Botany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic ExcellenceBotany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic Excellence
online college homework help
 
Origin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theoriesOrigin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theories
PrachiSontakke5
 
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon DolabaniHistory Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
fruinkamel7m
 
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Leonel Morgado
 
CNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscessCNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscess
Mohamed Rizk Khodair
 
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
parmarjuli1412
 
How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18
Celine George
 
puzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tensepuzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tense
OlgaLeonorTorresSnch
 
How To Maximize Sales Performance using Odoo 18 Diverse views in sales module
How To Maximize Sales Performance using Odoo 18 Diverse views in sales moduleHow To Maximize Sales Performance using Odoo 18 Diverse views in sales module
How To Maximize Sales Performance using Odoo 18 Diverse views in sales module
Celine George
 
2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx
mansk2
 
Cultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptxCultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptx
UmeshTimilsina1
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
The History of Kashmir Karkota Dynasty NEP.pptx
The History of Kashmir Karkota Dynasty NEP.pptxThe History of Kashmir Karkota Dynasty NEP.pptx
The History of Kashmir Karkota Dynasty NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFAMEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
Dr. Nasir Mustafa
 
Search Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo SlidesSearch Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo Slides
Celine George
 
How to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 PurchaseHow to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 Purchase
Celine George
 
Module 1: Foundations of Research
Module 1: Foundations of ResearchModule 1: Foundations of Research
Module 1: Foundations of Research
drroxannekemp
 
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living WorkshopLDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDM Mia eStudios
 
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
Dr. Nasir Mustafa
 
Botany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic ExcellenceBotany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic Excellence
online college homework help
 
Origin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theoriesOrigin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theories
PrachiSontakke5
 
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon DolabaniHistory Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
fruinkamel7m
 
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Leonel Morgado
 
CNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscessCNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscess
Mohamed Rizk Khodair
 
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
parmarjuli1412
 
How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18
Celine George
 
puzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tensepuzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tense
OlgaLeonorTorresSnch
 
How To Maximize Sales Performance using Odoo 18 Diverse views in sales module
How To Maximize Sales Performance using Odoo 18 Diverse views in sales moduleHow To Maximize Sales Performance using Odoo 18 Diverse views in sales module
How To Maximize Sales Performance using Odoo 18 Diverse views in sales module
Celine George
 
2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx
mansk2
 
Cultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptxCultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptx
UmeshTimilsina1
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFAMEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
Dr. Nasir Mustafa
 
Search Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo SlidesSearch Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo Slides
Celine George
 
How to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 PurchaseHow to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 Purchase
Celine George
 

SQL Server Stored procedures

  • 2. 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
  • 3. BATCH Batch is a logical group of SQL statements Run-time error will halt execution only of FURTHER steps Can break up multiple steps using GO Not available in all tools GO causes editing tool to send statements to that point for execution GO isn’t sent to SQL Server
  • 4. Format of SPROC’s CREATE PROCEDURE <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 (select) 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. 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
  • 12. Variables Create using DECLARE Need to start with ‘@’ Can use SQL data types or custom data types DECLARE @StudentName varchar(50)
  • 13. 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
  • 14. Decision Making SQL supports two structures for branching: IF CASE Both structures are similar to other languages (IF … THEN, SELECT CASE) Both structures tend to have specific places where used
  • 15. IF Blocks IF … ELSE No end if Need to use Begin/End if have more than one instruction to execute IF StartDate < EndDate Begin … End ELSE
  • 16. Simple Case Statement CASE Similar to SELECT CASE Compares one value to different cases CASE Category WHEN ‘pop_comp’ THEN ‘Popular Computing’ WHEN ‘mod_cook’ THEN ‘Modern Cooking’ END
  • 17. 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
  • 18. Looping (While) Typically used with a CURSOR Cursor data type allows a table to be stored in memory and each row/field to be accessed BREAK allows early exit from loop CONTINUE forces control to start of loop Working with sets is preferred over loops (SQL is about sets)
  • 19. Finding Identity Values When need to find the value used to identify the last row added @@Identity Scope_Identity Ident_Current
  • 20. @@Identity – System Variable Returns the last identity value used as a result of INSERT or SELECT INTO Not limited to current scope; may not get correct value Returns Null if operation failed or a value wasn’t generated Returns last number created if multiple inserts occur (i.e. SELECT INTO)
  • 21. Scope_Identity() Return the last identity values generated in any table in the current session. Returns values inserted only within the current scope Not affected by other operations.
  • 22. Ident_Current() Not limited by scope and session; Limited to a specified table (table name specified as an argument value).
  • 23. @@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
  • 24. Errors Errors can occur because of SQL statement Invalid syntax, or data type Errors can also reflect business rules Data doesn’t match requirements
  • 25. @@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
  • 26. Try/Catch Similar to .Net languages Need to include BEGIN/END BEGIN TRY <code> END TRY BEGIN CATCH <error handling code> END CATCH
  • 27. Raise Error Used to send information to calling program Syntax: RaisError (Message string OR Message ID, Severity, State) Severity – <14 information; 15-19 warning or user can correct; 20+ fatal State – way to differentiate problems if needed; typically use 1 RAISERROR (50001,16,1)
  • 28. Error Message Message ID or String Use ID if have custom or TSQL error to use Use String for ‘on the fly’ message Stored Error Messages are server-specific Can add message Number greater than 50000
  • 29. Custom Error Messages Messages can include a parameter with % to allow addition to message ‘ D’ – signed integer ‘ O’ – unsigned octal ‘ P’ – pointer ‘ S’ – string ‘ U’ – unsigned integer ‘ X’ or ‘x’ – unsigned hexadecimal
  • 30. Severity & State 1 – 18: Informational 11 – 16 typically raise error at client 19 – 25: Severe error 20+ is fatal error and connection will terminate State is ‘ad hoc’ and can help if same error happens in multiple places Range of 1 – 127
  • 31. Sample Error Message RaisError(“Operation cannot be completed because field %s cannot be null”,1,1,”fieldname”)
  • 32. Transactions Provides method for canceling an operation Can restore rows, columns to original state in event of error or business logic failure Use when changes will either be committed or discarded in entirety
  • 33. ACID Atomicity : All of the changes will be accepted or none of the changes will be accepted Consistency : Data is either in its original or changed state Isolation : If multiple transactions occur, data is never available in an intermediate state Durability : Once finished, all changes are complete and changes can only be done by another transaction/unit of work
  • 34. Using A Transaction Begin Tran: Identifies the start Commit Tran: Write changes Rollback Tran: Cancel changes Issue A Commit Or Rollback Or Connection Stays Open Until Terminated
  • 35. Locking & Concurrency Locking allows a transaction to ensure that it can rollback Prevents other operations from changing that data Concurrency refers to multiple actions running against database at the same time What happens if you want to change data I’m working with?
  • 36. Sample Locking Levels Database Table Extent (memory) Page (subset of extent) Key Row
  • 37. Cursors Processing based on each row not set operations Declare @Cursor Cursor Set @Cursor = Cursor For (select statement) Open @Cursor Fetch Next From @Cursor into (variables matching field list in select)
  • 38. Using a Cursor Declare @Students Cursor Set @Cursor = Cursor For (Select FirstName, LastName From Students) Open @Students While @@Fetch_Status = 0 Begin Fetch Next From @Students Into @First, @Last Print @First + ‘ ‘+ @Last End Close @Students Deallocate @Students
  • 39. @@Fetch_Status 0 success; -1 failed (read record outside recordset); -2 missing record (eg. someone else deleted)

Editor's Notes

  • #2: Stored Procedures 11/04/11
  • #16: Stored Procedures 11/04/11
  • #26: Stored Procedures 11/04/11
  翻译: