Module 8: Implementing Stored Procedures. Introducing Stored Procedures Creating, Modifying, Dropping, and Executing Stored Procedures Using Parameters.

Slides:



Advertisements
Similar presentations
Module 17 Tracing Access to SQL Server 2008 R2. Module Overview Capturing Activity using SQL Server Profiler Improving Performance with the Database Engine.
Advertisements

Stored Procedures and Functions Rose-Hulman Institute of Technology Curt Clifton.
Module 9: Implementing Stored Procedures. Introduction to Stored Procedures Creating Executing Modifying Dropping Using Parameters in Stored Procedures.
Module 8: Implementing Views. Overview Introduction Advantages Definition Modifying Data Through Views Optimizing Performance by Using Views.
Module 8: Monitoring SQL Server for Performance. Overview Why to Monitor SQL Server Performance Monitoring and Tuning Tools for Monitoring SQL Server.
Chapter 9: Creating Database Conventions & Standards MCITP Administrator: Microsoft SQL Server 2005 Database Server Infrastructure Design Study Guide (70-443)
Module 17 Storing XML Data in SQL Server® 2008 R2.
Stored Procedures A stored procedure is a named collection of SQL statements language. You can create stored procedures for commonly used functions and.
Module 3: Changes to Transact-SQL. Overview Accessing Object Information New Transact-SQL Syntax Changes to Objects Distributed Queries.
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
Module 7: Fundamentals of Administering Windows Server 2008.
Stored Procedures A stored procedure is a named collection of SQL statements language. You can create stored procedures for commonly used functions and.
Store Procedures Lesson 9. Skills Matrix Stored Procedures Stored procedures in SQL Server are similar to the procedures you write in other programming.
Defining Stored Procedures Named Collections of Transact-SQL Statements Encapsulate Repetitive Tasks Five Types (System, Local, Temporary, Remote, and.
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.
Dexterity | CONFIDENTIAL 2009 MRO | Analytics | Insights 1 Stored Procedures.
Module 1: Introduction to Transact-SQL
Module 9 Designing and Implementing Stored Procedures.
SQL/Lesson 4/Slide 1 of 45 Using Subqueries and Managing Databases Objectives In this lesson, you will learn to: *Use subqueries * Use subqueries with.
T-SQL Transact-SQL is microsoft implementation of SQL. It contains additional programming constracts T-SQL enables you to write programs that contain SQL.
Module 9: Introduction to Programming Objects. Overview Displaying the Text of a Programming Object Introduction to Views Advantages of Views Creating.
Module 4: Managing Security. Overview Implementing an Authentication Mode Assigning Login Accounts to Users and Roles Assigning Permissions to Users and.
Module 11: Programming Across Multiple Servers. Overview Introducing Distributed Queries Setting Up a Linked Server Environment Working with Linked Servers.
Module 14 Configuring Security for SQL Server Agent.
IMS 4212: Intro to SQL 1 Dr. Lawrence West, Management Dept., University of Central Florida Introduction to SQL—Topics Introduction to.
1 Chapter Overview Preparing to Upgrade Performing a Version Upgrade from Microsoft SQL Server 7.0 Performing an Online Database Upgrade from SQL Server.
Module 18 Querying XML Data in SQL Server® 2008 R2.
Module 8: Implementing Stored Procedures. Overview Implementing Stored Procedures Creating Parameterized Stored Procedures Working With Execution Plans.
Module 4 Designing and Implementing Views. Module Overview Introduction to Views Creating and Managing Views Performance Considerations for Views.
Module 3 Designing and Implementing Tables. Module Overview Designing Tables Working with Schemas Creating and Altering Tables.
Creating a dynamic search form with database paging Tony Rogerson SQL Server MVP Torver Computer Consultants.
06 | Modifying Data in SQL Server Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager.
Module 7: Modifying Data. Overview Using Transactions Inserting Data Deleting Data Updating Data Performance Considerations.
Module 7: Implementing Views. Overview Introducing Views Defining and Using Views Using Views to Optimize Performance.
Working with SQL Server Database Objects Faculty: Nguyen Ngoc Tu.
Database Security Cmpe 226 Fall 2015 By Akanksha Jain Jerry Mengyuan Zheng.
SQL Server 2012 Session: 1 Session: 12 Triggers Data Management Using Microsoft SQL Server.
Stored Procedures / Session 4/ 1 of 41 Session 4 Module 7: Introducing stored procedures Module 8: More about stored procedures.
Ch 5. Introducing More Database Objects. Database Objects Table (ch2) View (ch3) Stored Procedure Trigger Function User-defined types.
IMS 4212: Application Architecture and Intro to Stored Procedures 1 Dr. Lawrence West, Management Dept., University of Central Florida
Text TCS INTERNAL Oracle PL/SQL – Introduction. TCS INTERNAL PL SQL Introduction PLSQL means Procedural Language extension of SQL. PLSQL is a database.
Module 10 Merging Data and Passing Tables. Module Overview Using the MERGE Statement Implementing Table Types Using Table Types As Parameters.
Module 9: Using Advanced Techniques. Considerations for Querying Data Working with Data Types Cursors and Set-Based Queries Dynamic SQL Maintaining Query.
Module 8: Using Programming Objects for Data Retrieval.
SQL Triggers, Functions & Stored Procedures Programming Operations.
Module 6: Creating and Maintaining Indexes. Overview Creating Indexes Understanding Index Creation Options Maintaining Indexes Introducing Statistics.
Dynamic SQL Writing Efficient Queries on the Fly ED POLLACK AUTOTASK CORPORATION DATABASE OPTIMIZATION ENGINEER.
In this session, you will learn to: Create and manage views Implement a full-text search Implement batches Objectives.
Module 9: Implementing Functions. Overview Creating and Using Functions Working with Functions Controlling Execution Context.
Module 9: Implementing User-Defined Functions. Overview Introducing User-Defined Functions Implementing User-Defined Functions.
Views / Session 3/ 1 of 40 Session 3 Module 5: Implementing Views Module 6: Managing Views.
1 c6212 Advanced Database and Client Server MS SQL Server 2000 Stored Procedures and Parameters What ? Why ? How ?
Introduction to Structured Query Language (SQL) By Techandmate.comTechandmate.com Learn SQL Server With US.
Transact SQL (T-SQL) Creating Stored Procedures, Functions and Triggers SoftUni Team Technical Trainers Software University
Module 1: SQL Server Overview
User-defined functions, Procedures, Triggers and Transactions
Module T03d Software Engineering
Dynamic SQL Writing Efficient Queries on the Fly
PROCEDURES, CONDITIONAL LOGIC, EXCEPTION HANDLING, TRIGGERS
Module 10: Implementing Triggers
STORED PROCEDURES AND FUNCTION (9.6.1)
Module 7: Implementing Views
Dynamic SQL Writing Efficient Queries on the Fly
Module 5: Implementing Data Integrity by Using Constraints
20761B 10: Using Subqueries Module 10   Using Subqueries.
Using Table Expressions
SQL Server Stored Procedures.
Dynamic Sql Not so scary?
Presentation transcript:

Module 8: Implementing Stored Procedures

Introducing Stored Procedures Creating, Modifying, Dropping, and Executing Stored Procedures Using Parameters in Stored Procedures Handling Error Messages Working with Stored Procedures Overview

What Are Stored Procedures? Advantages of Stored Procedures Initial Processing of Stored Procedures Subsequent Processing of Stored Procedures Lesson: Introducing Stored Procedures

What Are Stored Procedures? Named Collections of Transact-SQL Statements Encapsulate Repetitive Tasks Accept Input Parameters and Return Output Parameter Values Return Status Value to Indicate Success or Failure Five Types (System, Local, Temporary, Remote, and Extended)

Advantages of Stored Procedures Share Application Logic Shield Database Schema Details Provide Security Mechanisms Improve Performance Reduce Network Traffic Reduce Vulnerability to SQL Injection Attacks

Initial Processing of Stored Procedures Entries into sysobjects and syscomments tables Compiled plan placed in procedure cache Creation Execution (first time or recompile) Optimization Parsing Compilation

Unused plan is aged out Execution PlanExecution Context Connection Connection 2 Connection Subsequent Processing of Stored Procedures Execution Plan Retrieved SELECT * FROM dbo.member WHERE member_no = ?

Lesson: Creating, Modifying, Dropping, and Executing Stored Procedures The CREATE PROCEDURE Statement Guidelines for Creating Stored Procedures The ALTER PROCEDURE Statement The DROP PROCEDURE Statement Stored Procedure Execution

The CREATE PROCEDURE Statement Create in Current Database Using the CREATE PROCEDURE Statement Can Nest to 32 Levels Use sp_help to Display Information USE Northwind GO CREATE PROC dbo.OverdueOrders AS SELECT * FROM dbo.Orders WHERE RequiredDate < GETDATE() AND ShippedDate IS Null GO USE Northwind GO CREATE PROC dbo.OverdueOrders AS SELECT * FROM dbo.Orders WHERE RequiredDate < GETDATE() AND ShippedDate IS Null GO

dbo User Should Own All Objects Create, Test, and Troubleshoot Avoid sp_ Prefix in Stored Procedure Names Use Same Connection Settings for All Stored Procedures Minimize Use of Temporary Stored Procedures One Stored Procedure for One Task Guidelines for Creating Stored Procedures

The ALTER PROCEDURE Statement Altering Stored Procedures  Include any options in ALTER PROCEDURE  Does not affect nested stored procedures USE Northwind GO ALTER PROC dbo.OverdueOrders AS SELECT CONVERT(char(8), RequiredDate, 1) RequiredDate, CONVERT(char(8), OrderDate, 1) OrderDate, OrderID, CustomerID, EmployeeID FROM Orders WHERE RequiredDate < GETDATE() AND ShippedDate IS Null ORDER BY RequiredDate GO USE Northwind GO ALTER PROC dbo.OverdueOrders AS SELECT CONVERT(char(8), RequiredDate, 1) RequiredDate, CONVERT(char(8), OrderDate, 1) OrderDate, OrderID, CustomerID, EmployeeID FROM Orders WHERE RequiredDate < GETDATE() AND ShippedDate IS Null ORDER BY RequiredDate GO

The DROP PROCEDURE Statement Dropping Stored Procedures  Execute the sp_depends stored procedure to determine whether objects depend on the stored procedure  Procedure information is removed from the sysobjects and syscomments system tables Required Permission  Procedure owner  Members of db_owner, db_ddladmin, and sysadmin roles USE Northwind GO DROP PROC dbo.OverdueOrders GO USE Northwind GO DROP PROC dbo.OverdueOrders GO

Stored Procedure Execution Executing a Stored Procedure by Itself Executing a Stored Procedure Within an INSERT Statement EXEC OverdueOrders INSERT INTO Customers EXEC EmployeeCustomer INSERT INTO Customers EXEC EmployeeCustomer

Lab A: Creating Stored Procedures Exercise 1: Writing and Executing a Stored Procedure Exercise 2: Locating Stored Procedure Information

Lesson: Using Parameters in Stored Procedures Input Parameters Methods of Setting Parameter Values Return Values Using OUTPUT Parameters Return Values Using the RETURN Statement Stored Procedure Recompile

Input Parameters Validate All Incoming Parameter Values First Provide Appropriate Default Values and Include Null Checks CREATE PROCEDURE dbo.[Year to Year DateTime = DateTime = Null AS IS Null = dateadd(yy,-1,GetDate()) IS Null = GetDate() IF > 365 BEGIN RAISERROR('The maximum timespan allowed for this report is one year.', 14, 1) RETURN END SELECT O.ShippedDate,O.OrderID,OS.Subtotal, DATENAME(yy,ShippedDate) AS Year FROM ORDERS O INNER JOIN [Order Subtotals] OS ON O.OrderID = OS.OrderID WHERE O.ShippedDate GO CREATE PROCEDURE dbo.[Year to Year DateTime = DateTime = Null AS IS Null = dateadd(yy,-1,GetDate()) IS Null = GetDate() IF > 365 BEGIN RAISERROR('The maximum timespan allowed for this report is one year.', 14, 1) RETURN END SELECT O.ShippedDate,O.OrderID,OS.Subtotal, DATENAME(yy,ShippedDate) AS Year FROM ORDERS O INNER JOIN [Order Subtotals] OS ON O.OrderID = OS.OrderID WHERE O.ShippedDate GO

Methods of Setting Parameter Values Passing Values by Parameter Name Passing Values by Position EXEC AddCustomer 'ALFKI2', 'Alfreds Futterkiste', 'Maria Anders', 'Sales Representative', 'Obere Str. 57', 'Berlin', NULL, '12209', 'Germany', ' ' EXEC = = 'Maria = 'Alfreds = 'Sales = 'Obere Str. = = = = ' ' EXEC = = 'Maria = 'Alfreds = 'Sales = 'Obere Str. = = = = ' '

CREATE PROCEDURE int OUTPUT AS GO smallint EXECUTE MathTutor OUTPUT SELECT 'The result is: The result is: 30 CREATE PROCEDURE int OUTPUT AS GO smallint EXECUTE MathTutor OUTPUT SELECT 'The result is: The result is: 30 Return Values Using OUTPUT Parameters Results of Stored Procedure Executing Stored Procedure Creating Stored Procedure

CREATE PROC nvarchar(10) ) AS INSERT Employees(LastName,FirstName) RETURN SCOPE_IDENTITY() Go int SELECT EmployeeID, LastName, FirstName FROM Employees WHERE EmployeeId EmployeeID LastName FirstName Hankin Alex CREATE PROC nvarchar(10) ) AS INSERT Employees(LastName,FirstName) RETURN SCOPE_IDENTITY() Go int SELECT EmployeeID, LastName, FirstName FROM Employees WHERE EmployeeId EmployeeID LastName FirstName Hankin Alex Return Values Using the RETURN Statement Result Executing Stored Procedure Creating Stored Procedure

Stored Procedure Recompile Recompile When  Stored procedure returns widely varying result sets  A new index is added to an underlying table  The parameter value is atypical Recompile by Using  CREATE PROCEDURE [WITH RECOMPILE]  EXECUTE [WITH RECOMPILE]  sp_recompile

Lesson: Handling Error Messages Error Messages Demonstration: Handling Error Messages

Error Messages RETURN Statement Exits Query or Procedure Unconditionally sp_addmessage Creates Custom Error Messages Contains Error Number for Last Executed Statement RAISERROR Statement  Returns user-defined or system error message  Sets system flag to record error

Demonstration: Handling Error Messages Handling error messages

Lesson: Working with Stored Procedures Dynamic SQL in Stored Procedures SQL Injection Extended Stored Procedures Performance Diagnosis Tools Best Practices

Dynamic SQL in Stored Procedures Dynamic Search Conditions The IN Clause Administrative Functions = 'SELECT * FROM CUSTOMERS WHERE 1=1' IF > 0 EXEC = 'SELECT * FROM CUSTOMERS WHERE 1=1' IF > 0 EXEC = 'SELECT ProductID, ProductName, UnitPrice FROM Products WHERE ProductID IN (' + + ')' = 'SELECT ProductID, ProductName, UnitPrice FROM Products WHERE ProductID IN (' + + ')'

SQL Injection A Technique to Inject SQL Command as an Input Caused by Passing User Input Directly to SQL Code How to Avoid SQL Injection  Never trust user input  Avoid dynamic SQL  Execute with least privilege  Store secrets securely  Exceptions should divulge minimal information

Extended Stored Procedures Characteristics of Extended Stored Procedures:  Programmed using open data services API  Can include C and Microsoft Visual C++ features  Can contain multiple functions  Can be called from a client or SQL server  Can be added to the master database only EXEC master..xp_cmdshell 'dir c:\'

Performance Diagnosis Tools Windows 2000 System Monitor  Object: SQL Server: Cache Manager  Object: SQL Statistics SQL Profiler  Can monitor events  Can test each statement in a stored procedure

Design Each Stored Procedure to Accomplish a Single Task Validate Data Before You Begin Transactions Use the Same Connection Settings for All Stored Procedures Use WITH ENCRYPTION to Hide Text of Stored Procedures Verify Input Parameters Best Practices

Lab B: Creating Stored Procedures Using Parameters Exercise 1: Using the Create Stored Procedure Wizard Exercise 2: Using Error Handling in Stored Procedures Exercise 3: Customizing Error Messages Exercise 4: Using Return Codes If Time Permits  Executing Extended Stored Procedures  Tracing Stored Procedures Using SQL Profiler