Stored Procedures, Transactions, and Error-Handling

Slides:



Advertisements
Similar presentations
AN INTRODUCTION TO PL/SQL Mehdi Azarmi 1. Introduction PL/SQL is Oracle's procedural language extension to SQL, the non-procedural relational database.
Advertisements

PL/SQL. Introduction to PL/SQL PL/SQL is the procedure extension to Oracle SQL. It is used to access an Oracle database from various environments (e.g.
Chapter 8 Embedded SQL.
Chapter 4B: More Advanced PL/SQL Programming
Fundamentals, Design, and Implementation, 9/e Chapter 11 Managing Databases with SQL Server 2000.
1 Chapter 4 The Fundamentals of VBA, Macros, and Command Bars.
A Guide to Oracle9i1 Advanced SQL And PL/SQL Topics Chapter 9.
A Guide to SQL, Seventh Edition. Objectives Embed SQL commands in PL/SQL programs Retrieve single rows using embedded SQL Update a table using embedded.
ASP.NET Programming with C# and SQL Server First Edition Chapter 8 Manipulating SQL Server Databases with ASP.NET.
Guide To UNIX Using Linux Third Edition
COMP 5138 Relational Database Management Systems Semester 2, 2007 Lecture 8A Transaction Concept.
Bordoloi and Bock CURSORS. Bordoloi and Bock CURSOR MANIPULATION To process an SQL statement, ORACLE needs to create an area of memory known as the context.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
Cursor and Exception Handling By Nidhi Bhatnagar.
Module 12 Handling Errors in T-SQL Code. Module Overview Understanding T-SQL Error Handling Implementing T-SQL Error Handling Implementing Structured.
IMS 4212: Application Architecture and Intro to Stored Procedures 1 Dr. Lawrence West, Management Dept., University of Central Florida
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor Ms. Arwa.
Chapter 7 Advanced SQL Database Systems: Design, Implementation, and Management, Sixth Edition, Rob and Coronel.
Lecture 4 PL/SQL language. PL/SQL – procedural SQL Allows combining procedural and SQL code PL/SQL code is compiled, including SQL commands PL/SQL code.
Dinamic SQL & Cursor. Why Dinamic SQL ? Sometimes there is a need to dynamically create a SQL statement on the fly and then run that command. This can.
T-SQL Transact-SQL is microsoft implementation of SQL. It contains additional programming constracts T-SQL enables you to write programs that contain SQL.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
1 Definition of a subquery Nested subqueries Correlated subqueries The ISNULL function Derived tables The EXISTS operator Mixing data types: CAST & CONVERT.
15/10/20151 PHP & MySQL 'Slide materials are based on W3Schools PHP tutorial, 'PHP website 'MySQL website.
PHP MySQL Introduction. MySQL is the most popular open-source database system. What is MySQL? MySQL is a database. The data in MySQL is stored in database.
Overview · What is PL/SQL · Advantages of PL/SQL · Basic Structure of a PL/SQL Block · Procedure · Function · Anonymous Block · Types of Block · Declaring.
Flow of Control Part 1: Selection
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Database structure and space Management. Database Structure An ORACLE database has both a physical and logical structure. By separating physical and logical.
Programmatic SQL Shaista Khan CS 157B. Topic Embedded SQL statements in high-level programming languages.
CIS4368: Advanced DatabaseSlide # 1 PL/SQL Dr. Peeter KirsSpring, 2003 PL/SQL.
8 1 Chapter 8 Advanced SQL Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Chapter 15 Introduction to PL/SQL. Chapter Objectives  Explain the benefits of using PL/SQL blocks versus several SQL statements  Identify the sections.
What is a Package? A package is an Oracle object, which holds other objects within it. Objects commonly held within a package are procedures, functions,
Chapter 8 Advanced SQL Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
A Guide to SQL, Eighth Edition Chapter Eight SQL Functions and Procedures.
G. Green 1.  Options include:  Script Files  already covered  APIs  last course topic  Database-Stored Code  our focus 2.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
implicit and an explicit cursor
Session 1 Module 1: Introduction to Data Integrity
1 Intro stored procedures Declaring parameters Using in a sproc Intro to transactions Concurrency control & recovery States of transactions Desirable.
Learningcomputer.com SQL Server 2008 –Views, Functions and Stored Procedures.
Stored Procedures / Session 4/ 1 of 41 Session 4 Module 7: Introducing stored procedures Module 8: More about stored procedures.
IMS 4212: Constraints & Triggers 1 Dr. Lawrence West, Management Dept., University of Central Florida Stored Procedures in SQL Server.
Text TCS INTERNAL Oracle PL/SQL – Introduction. TCS INTERNAL PL SQL Introduction PLSQL means Procedural Language extension of SQL. PLSQL is a database.
Unit-8 Introduction Of MySql. Types of table in PHP MySQL supports various of table types or storage engines to allow you to optimize your database. The.
SQL Triggers, Functions & Stored Procedures Programming Operations.
1 Section 10 - Embedded SQL u Many computer languages allow you to embed SQL statements within the code (e.g. COBOL, PowerBuilder, C++, PL/SQL, etc.) u.
Dynamic SQL Writing Efficient Queries on the Fly ED POLLACK AUTOTASK CORPORATION DATABASE OPTIMIZATION ENGINEER.
CS422 Principles of Database Systems Stored Procedures and Triggers Chengyu Sun California State University, Los Angeles.
In this session, you will learn to: Create and manage views Implement a full-text search Implement batches Objectives.
1. Advanced SQL Functions Procedural Constructs Triggers.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
ASP.NET Programming with C# and SQL Server First Edition
Unit 2 Technology Systems
A Guide to SQL, Seventh Edition
Dynamic SQL Writing Efficient Queries on the Fly
SQL and SQL*Plus Interaction
Interacting with the Oracle Server
PL/SQL.
Programmability by Adrienne Watt.
Dynamic SQL Writing Efficient Queries on the Fly
PL/SQL Scripting in Oracle:
The PROCESS of Queries John Deardurff
The PROCESS of Queries John Deardurff
Chapter 8 Advanced SQL.
CodePainter Revolution Trainer Course
Chapter 11 Managing Databases with SQL Server 2000
COP 2700 – Data Structures (SQL)
Presentation transcript:

Stored Procedures, Transactions, and Error-Handling 4/23/2017 Stored Procedures, Transactions, and Error-Handling BIT275/276 Instructor: Craig Duckett Email: cduckett@cascadia.edu http://www.dotnet-tricks.com/Tutorial/sqlserver/IbUO310312-Different-Types-of-SQL-Server-Stored-Procedures.html http://www.dotnet-tricks.com/Tutorial/sqlserver/KY3T010412-Different-Types-of-SQL-Server-Functions.html

Stored Procedure vs. View A Stored Procedure: accepts parameters can NOT be used as building block in a larger query can contain several statements, loops, IF ELSE, etc. can perform modifications to one or several tables can NOT be used as the target of an INSERT, UPDATE or DELETE statement. A View: does NOT accept parameters CAN be used as building block in a larger query can contain only one single SELECT query can NOT perform modifications to any table but can (sometimes) be used as the target of an INSERT, UPDATE or DELETE statement.

Stored Procedure vs. Function Basic Difference Function must return a value but in Stored Procedure it is optional ( Procedure can return zero or n values). Functions can have only input parameters for it whereas Procedures can have input/output parameters . Functions can be called from Procedure whereas Procedures cannot be called from Function. Advance Difference Procedure allows SELECT as well as DML(INSERT/UPDATE/DELETE) statement in it whereas Function allows only SELECT statement in it. Procedures can not be utilized in a SELECT statement whereas Function can be embedded in a SELECT statement. Stored Procedures can NOT be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section whereas Function can be. The most important feature of stored procedures over function is to retention and reuse the execution plan while in case of function it will be compiled every time. Functions that return tables can be treated as another rowset. This can be used in JOINs with other tables. Inline Function can be though of as views that take parameters and can be used in JOINs and other Rowset operations. Exception can be handled by TRY-CATCH block in a Procedure whereas a TRY-CATCH block can NOT be used in a Function. We can go for Transaction Management in Procedure whereas we can't go in Function.

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 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 Stored Procedures 4/23/2017 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 END 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 Stored Procedures 4/23/2017 @@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 Declare @Cursor Cursor 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)