SlideShare une entreprise Scribd logo
1  sur  39
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 Persons
        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, created/maintained automatically
 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 variable, created/maintained automatically
 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, created/maintained automatically
 Value set after each SQL statement;
 0 (zero) 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 to server
    ID Number must be 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 (range can vary – not exact)
    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


 Be sure to issue a Commit or Rollback
    Connection Stays Open Until Transaction is 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)

Contenu connexe

Tendances

Lecture 2. MS SQL. Stored procedures.
Lecture 2. MS SQL. Stored procedures.Lecture 2. MS SQL. Stored procedures.
Lecture 2. MS SQL. Stored procedures.Alexey Furmanov
 
3963066 pl-sql-notes-only
3963066 pl-sql-notes-only3963066 pl-sql-notes-only
3963066 pl-sql-notes-onlyAshwin Kumar
 
Cursors, triggers, procedures
Cursors, triggers, proceduresCursors, triggers, procedures
Cursors, triggers, proceduresVaibhav Kathuria
 
pl/sql Procedure
pl/sql Procedurepl/sql Procedure
pl/sql ProcedurePooja Dixit
 
PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts Bharat Kalia
 
oracle plsql training | oracle online training | oracle plsql demo | oracle p...
oracle plsql training | oracle online training | oracle plsql demo | oracle p...oracle plsql training | oracle online training | oracle plsql demo | oracle p...
oracle plsql training | oracle online training | oracle plsql demo | oracle p...Nancy Thomas
 
Oracle SQL, PL/SQL best practices
Oracle SQL, PL/SQL best practicesOracle SQL, PL/SQL best practices
Oracle SQL, PL/SQL best practicesSmitha Padmanabhan
 
Stored-Procedures-Presentation
Stored-Procedures-PresentationStored-Procedures-Presentation
Stored-Procedures-PresentationChuck Walker
 
ORACLE PL SQL FOR BEGINNERS
ORACLE PL SQL FOR BEGINNERSORACLE PL SQL FOR BEGINNERS
ORACLE PL SQL FOR BEGINNERSmohdoracle
 

Tendances (18)

Sql Functions And Procedures
Sql Functions And ProceduresSql Functions And Procedures
Sql Functions And Procedures
 
Chapter 4 functions, views, indexing
Chapter 4  functions, views, indexingChapter 4  functions, views, indexing
Chapter 4 functions, views, indexing
 
Lecture 2. MS SQL. Stored procedures.
Lecture 2. MS SQL. Stored procedures.Lecture 2. MS SQL. Stored procedures.
Lecture 2. MS SQL. Stored procedures.
 
3963066 pl-sql-notes-only
3963066 pl-sql-notes-only3963066 pl-sql-notes-only
3963066 pl-sql-notes-only
 
Intro to tsql
Intro to tsqlIntro to tsql
Intro to tsql
 
SQL
SQLSQL
SQL
 
Cursors, triggers, procedures
Cursors, triggers, proceduresCursors, triggers, procedures
Cursors, triggers, procedures
 
Store procedures
Store proceduresStore procedures
Store procedures
 
pl/sql Procedure
pl/sql Procedurepl/sql Procedure
pl/sql Procedure
 
PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts
 
Oracle: PLSQL Introduction
Oracle: PLSQL IntroductionOracle: PLSQL Introduction
Oracle: PLSQL Introduction
 
Oracle: Procedures
Oracle: ProceduresOracle: Procedures
Oracle: Procedures
 
oracle plsql training | oracle online training | oracle plsql demo | oracle p...
oracle plsql training | oracle online training | oracle plsql demo | oracle p...oracle plsql training | oracle online training | oracle plsql demo | oracle p...
oracle plsql training | oracle online training | oracle plsql demo | oracle p...
 
Oracle SQL, PL/SQL best practices
Oracle SQL, PL/SQL best practicesOracle SQL, PL/SQL best practices
Oracle SQL, PL/SQL best practices
 
PLSQL Tutorial
PLSQL TutorialPLSQL Tutorial
PLSQL Tutorial
 
Stored-Procedures-Presentation
Stored-Procedures-PresentationStored-Procedures-Presentation
Stored-Procedures-Presentation
 
4. plsql
4. plsql4. plsql
4. plsql
 
ORACLE PL SQL FOR BEGINNERS
ORACLE PL SQL FOR BEGINNERSORACLE PL SQL FOR BEGINNERS
ORACLE PL SQL FOR BEGINNERS
 

En vedette

Tools developed
Tools developedTools developed
Tools developedS Cunha
 
Complete list of all sap abap keywords
Complete list of all sap abap keywordsComplete list of all sap abap keywords
Complete list of all sap abap keywordsPrakash Thirumoorthy
 
Test de Boston
Test de BostonTest de Boston
Test de Bostonmireiabi
 
87683689 ooad-lab-record
87683689 ooad-lab-record87683689 ooad-lab-record
87683689 ooad-lab-recordPon Venkatesh
 
Seating arrangement
Seating arrangementSeating arrangement
Seating arrangementBousong En
 
Project on examination management system
Project on examination management systemProject on examination management system
Project on examination management systemSagar Mandal
 
Library Management System
Library Management SystemLibrary Management System
Library Management SystemAditya Shah
 
Ames cloud a framework of adaptive mobile video streaming and efficient socia...
Ames cloud a framework of adaptive mobile video streaming and efficient socia...Ames cloud a framework of adaptive mobile video streaming and efficient socia...
Ames cloud a framework of adaptive mobile video streaming and efficient socia...Nagendra Nayak Bharothu
 
Ops 571 free final exam sg 2014
Ops 571  free final exam sg 2014Ops 571  free final exam sg 2014
Ops 571 free final exam sg 2014Rogue Phoenix
 

En vedette (12)

Tools developed
Tools developedTools developed
Tools developed
 
Complete list of all sap abap keywords
Complete list of all sap abap keywordsComplete list of all sap abap keywords
Complete list of all sap abap keywords
 
Test percepción.
Test percepción.Test percepción.
Test percepción.
 
Test de Boston
Test de BostonTest de Boston
Test de Boston
 
87683689 ooad-lab-record
87683689 ooad-lab-record87683689 ooad-lab-record
87683689 ooad-lab-record
 
Seating arrangement
Seating arrangementSeating arrangement
Seating arrangement
 
Design of a Computerized Inventory Management System for Supermarkets
Design of a Computerized Inventory Management System for SupermarketsDesign of a Computerized Inventory Management System for Supermarkets
Design of a Computerized Inventory Management System for Supermarkets
 
Project on examination management system
Project on examination management systemProject on examination management system
Project on examination management system
 
Abstract
AbstractAbstract
Abstract
 
Library Management System
Library Management SystemLibrary Management System
Library Management System
 
Ames cloud a framework of adaptive mobile video streaming and efficient socia...
Ames cloud a framework of adaptive mobile video streaming and efficient socia...Ames cloud a framework of adaptive mobile video streaming and efficient socia...
Ames cloud a framework of adaptive mobile video streaming and efficient socia...
 
Ops 571 free final exam sg 2014
Ops 571  free final exam sg 2014Ops 571  free final exam sg 2014
Ops 571 free final exam sg 2014
 

Similaire à Stored procedures (20)

CIS 282 Final Review
CIS 282 Final ReviewCIS 282 Final Review
CIS 282 Final Review
 
Intro to tsql unit 11
Intro to tsql   unit 11Intro to tsql   unit 11
Intro to tsql unit 11
 
CIS160 final review
CIS160 final reviewCIS160 final review
CIS160 final review
 
Intro to tsql unit 14
Intro to tsql   unit 14Intro to tsql   unit 14
Intro to tsql unit 14
 
Database development coding standards
Database development coding standardsDatabase development coding standards
Database development coding standards
 
PLSQLmy Updated (1).pptx
PLSQLmy Updated (1).pptxPLSQLmy Updated (1).pptx
PLSQLmy Updated (1).pptx
 
Procedures functions structures in VB.Net
Procedures  functions  structures in VB.NetProcedures  functions  structures in VB.Net
Procedures functions structures in VB.Net
 
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
 
Module04
Module04Module04
Module04
 
7a advanced tsql
7a   advanced tsql7a   advanced tsql
7a advanced tsql
 
Database programming
Database programmingDatabase programming
Database programming
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
PLSQL
PLSQLPLSQL
PLSQL
 
Stored procedures
Stored proceduresStored procedures
Stored procedures
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
 
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
 
L9 l10 server side programming
L9 l10  server side programmingL9 l10  server side programming
L9 l10 server side programming
 
Sql Server 2008 New Programmability Features
Sql Server 2008 New Programmability FeaturesSql Server 2008 New Programmability Features
Sql Server 2008 New Programmability Features
 
Mysqlppt
MysqlpptMysqlppt
Mysqlppt
 
Mysqlppt
MysqlpptMysqlppt
Mysqlppt
 

Plus de Randy Riness @ South Puget Sound Community College

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

3 sql overview
3 sql overview3 sql overview
3 sql overview
 
Normalization
NormalizationNormalization
Normalization
 
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
 

Dernier

Dust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEDust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEaurabinda banchhor
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
EMBODO Lesson Plan Grade 9 Law of Sines.docx
EMBODO Lesson Plan Grade 9 Law of Sines.docxEMBODO Lesson Plan Grade 9 Law of Sines.docx
EMBODO Lesson Plan Grade 9 Law of Sines.docxElton John Embodo
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
The Contemporary World: The Globalization of World Politics
The Contemporary World: The Globalization of World PoliticsThe Contemporary World: The Globalization of World Politics
The Contemporary World: The Globalization of World PoliticsRommel Regala
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationRosabel UA
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
Presentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptxPresentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptxRosabel UA
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 

Dernier (20)

Dust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEDust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSE
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
EMBODO Lesson Plan Grade 9 Law of Sines.docx
EMBODO Lesson Plan Grade 9 Law of Sines.docxEMBODO Lesson Plan Grade 9 Law of Sines.docx
EMBODO Lesson Plan Grade 9 Law of Sines.docx
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
The Contemporary World: The Globalization of World Politics
The Contemporary World: The Globalization of World PoliticsThe Contemporary World: The Globalization of World Politics
The Contemporary World: The Globalization of World Politics
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translation
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
Presentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptxPresentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptx
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 

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 Persons 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, created/maintained automatically  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 variable, created/maintained automatically  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, created/maintained automatically  Value set after each SQL statement;  0 (zero) 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 to server  ID Number must be 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 (range can vary – not exact)  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  Be sure to issue a Commit or Rollback  Connection Stays Open Until Transaction is 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)