Module 8: Using Programming Objects for Data Retrieval.

Slides:



Advertisements
Similar presentations
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Advertisements

Module 10: Implementing User-defined Functions. Overview What Is a User-defined Function? Defining Examples.
Introduction to Structured Query Language (SQL)
Module 9: Implementing Stored Procedures. Introduction to Stored Procedures Creating Executing Modifying Dropping Using Parameters in Stored Procedures.
A Guide to Oracle9i1 Advanced SQL And PL/SQL Topics Chapter 9.
Fundamentals, Design, and Implementation, 9/e Chapter 7 Using SQL in Applications.
Chapter 7 Advanced SQL Database Systems: Design, Implementation, and Management, Sixth Edition, Rob and Coronel.
Database Systems More SQL Database Design -- More SQL1.
Introduction to Structured Query Language (SQL)
Module 9 Designing an XML Strategy. Module 9: Designing an XML Strategy Designing XML Storage Designing a Data Conversion Strategy Designing an XML Query.
Chapter 9: Creating Database Conventions & Standards MCITP Administrator: Microsoft SQL Server 2005 Database Server Infrastructure Design Study Guide (70-443)
Overview What is SQL Server? Creating databases Administration Security Backup.
Module 9: Managing Schema Objects. Overview Naming guidelines for identifiers in schema object definitions Storage and structure of schema objects Implementing.
A Guide to SQL, Eighth Edition Chapter Three Creating Tables.
Module 3: Changes to Transact-SQL. Overview Accessing Object Information New Transact-SQL Syntax Changes to Objects Distributed Queries.
Functions Lesson 10. Skills Matrix Function A function is a piece of code or routine that accepts parameters and stored as an object in SQL Server. The.
CSE314 Database Systems More SQL: Complex Queries, Triggers, Views, and Schema Modification Doç. Dr. Mehmet Göktürk src: Elmasri & Navanthe 6E Pearson.
Module 8: Implementing Stored Procedures. Introducing Stored Procedures Creating, Modifying, Dropping, and Executing Stored Procedures Using Parameters.
Module 9 Designing and Implementing Stored Procedures.
Module 9: Introduction to Programming Objects. Overview Displaying the Text of a Programming Object Introduction to Views Advantages of Views Creating.
Module 11: Programming Across Multiple Servers. Overview Introducing Distributed Queries Setting Up a Linked Server Environment Working with Linked Servers.
5/24/01 Leveraging SQL Server 2000 in ColdFusion Applications December 9, 2003 Chris Lomvardias SRA International
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
Module 4 Designing and Implementing Views. Module Overview Introduction to Views Creating and Managing Views Performance Considerations for Views.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Module 3 Designing and Implementing Tables. Module Overview Designing Tables Working with Schemas Creating and Altering Tables.
Dec 8, 2003Murali Mani Constraints B term 2004: lecture 15.
SQL Server 2005 Implementation and Maintenance Chapter 3: Tables and Views.
Module 4: Implementing Data Integrity
06 | Modifying Data in SQL Server Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers.
Visual Programing SQL Overview Section 1.
Module 11 Authorizing Users to Access Resources. Module Overview Authorizing User Access to Objects Authorizing Users to Execute Code Configuring Permissions.
Slide 1 of 19Session 13 Ver. 1.0 Querying and Managing Data Using SQL Server 2005 In this session, you will learn to: Implement stored procedures Implement.
Chapter 5 : Integrity And Security  Domain Constraints  Referential Integrity  Security  Triggers  Authorization  Authorization in SQL  Views 
IT System Administration Lesson 3 Dr Jeffrey A Robinson.
Session 1 Module 1: Introduction to Data Integrity
Learningcomputer.com SQL Server 2008 –Views, Functions and Stored Procedures.
05 | SET Operators, Windows Functions, and Grouping Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program.
Slide 1 Chapter 7 – Part 3 Stored Procedure, Function &Trigger.
SQL Server 2012 Session: 1 Session: 12 Triggers Data Management Using Microsoft SQL Server.
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
Module 10 Merging Data and Passing Tables. Module Overview Using the MERGE Statement Implementing Table Types Using Table Types As Parameters.
CSCI N311: Oracle Database Programming 5-1 Chapter 15: Changing Data: insert, update, delete Insert Rollback Commit Update Delete Insert Statement –Allows.
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
Module 9: Using Advanced Techniques. Considerations for Querying Data Working with Data Types Cursors and Set-Based Queries Dynamic SQL Maintaining Query.
Constraints and Views Chap. 3-5 continued (7 th ed. 5-7)
CSC314 DAY 8 Introduction to SQL 1. Chapter 6 © 2013 Pearson Education, Inc. Publishing as Prentice Hall SQL OVERVIEW  Structured Query Language  The.
SQL Triggers, Functions & Stored Procedures Programming Operations.
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.
Module 5: Working with Subqueries. Writing Basic Subqueries Writing Correlated Subqueries Comparing Subqueries with Joins and Temporary Tables Using Common.
Data Integrity & Indexes / Session 1/ 1 of 37 Session 1 Module 1: Introduction to Data Integrity Module 2: Introduction to Indexes.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
Fundamentals of DBMS Notes-1.
Implementing Views Advanced Database Dr. AlaaEddin Almabhouh.
Creating Database Triggers
Module 7: Implementing Views
Module 5: Implementing Data Integrity by Using Constraints
Overview Implementing Triggers Implementing XML Schemas.
Advanced SQL: Views & Triggers
Microsoft SQL Server 2014 for Oracle DBAs Module 7
Contents Preface I Introduction Lesson Objectives I-2
Chapter 7 Using SQL in Applications
Chapter 8 Advanced SQL.
IST 318 Database Administration
Presentation transcript:

Module 8: Using Programming Objects for Data Retrieval

Overview of Views Overview of User-Defined Functions Overview of Stored Procedures Overview of Triggers Writing Distributed Queries

Lesson 1: Overview of Views What Are Views? Creating and Managing a View Considerations When Creating Views Restrictions for Modifying Data by Using Views Indexed Views Indexed View Example Partitioned Views Partitioned View Example

What Are Views? Employee (table) EmployeeIDLastNameFirstNameTitle… 287Mensa-AnnanTeteMr.… 288AbbasSyedMr.… 289ValdezRachelNULL… vEmployee (view) LastNameFirstName Mensa-AnnanTete AbbasSyed ValdezRachel A View is a stored query producing a virtual table

Creating or Modifying a view Creating and Managing a View [CREATE|ALTER] VIEW HumanResources.vEmployee AS BEGIN SELECT EmployeeID, FirstName, LastName, Address FROM HumanResources.Employee END [CREATE|ALTER] VIEW HumanResources.vEmployee AS BEGIN SELECT EmployeeID, FirstName, LastName, Address FROM HumanResources.Employee END Deleting a view DROP VIEW HumanResources.vEmployee

Considerations When Creating Views RestrictionDescription Column Limit Total number of columns referenced in the view cannot exceed 1024 COMPUTE Cannot be used in a CREATE VIEW definition ORDER BY Cannot be used in views, inline functions, derived tables, and subqueries INTO Cannot be used with the SELECT statement in a view definition Temporary table Cannot be referenced in a view GO CREATE VIEW must be alone in a single batch SELECT * Can be used in a view definition if the SCHEMABINDING clause is not specified

Restrictions For Modifying Data by Using Views Table columns must be referenced directly Use an INSTEAD OF trigger Cannot be affected by GROUP BY, HAVING, or DISTINCT clauses. Data must follow the restrictions on the modified columns Table columns must be referenced directly Use an INSTEAD OF trigger Cannot be affected by GROUP BY, HAVING, or DISTINCT clauses. Data must follow the restrictions on the modified columns Statements must modify columns from only one base table Follow criteria when WITH CHECK OPTION is used INSERT must specify values for all non-nullable columns Statements must modify columns from only one base table Follow criteria when WITH CHECK OPTION is used INSERT must specify values for all non-nullable columns Restrictions to columns when modifying data: Restrictions to writing statements that modify data:

Indexed Views Views can be indexed using CREATE INDEX Should not be used for views whose underlying data is updated frequently Columns must be listed explicitly Views must be created with the SCHEMABINDING option Views can be indexed using CREATE INDEX Should not be used for views whose underlying data is updated frequently Columns must be listed explicitly Views must be created with the SCHEMABINDING option Views can be indexed using CREATE INDEX Should not be used for views whose underlying data is updated frequently Columns must be listed explicitly Views must be created with the SCHEMABINDING option Indexed View Details An Indexed View is a view for which a unique clustered index has been created.

Creating an Indexed View Indexed View Example CREATE VIEW vwDiscount WITH SCHEMABINDING AS SELECT SUM(UnitPrice*OrderQty)AS SumPrice, SUM(UnitPrice*OrderQty*(1.00-UnitPriceDiscount))AS SumDiscountPrice, SUM(UnitPrice*OrderQty*UnitPriceDiscount)AS SumDiscountPrice2, COUNT_BIG(*) AS Count, ProductID FROM Sales.SalesOrderDetail GROUP BY ProductID GO CREATE UNIQUE CLUSTERED INDEX vwDiscount Ind ON vwDiscount (ProductID) CREATE VIEW vwDiscount WITH SCHEMABINDING AS SELECT SUM(UnitPrice*OrderQty)AS SumPrice, SUM(UnitPrice*OrderQty*(1.00-UnitPriceDiscount))AS SumDiscountPrice, SUM(UnitPrice*OrderQty*UnitPriceDiscount)AS SumDiscountPrice2, COUNT_BIG(*) AS Count, ProductID FROM Sales.SalesOrderDetail GROUP BY ProductID GO CREATE UNIQUE CLUSTERED INDEX vwDiscount Ind ON vwDiscount (ProductID)

Partitioned Views Views can be indexed using CREATE INDEX Should not be used for views whose underlying data is updated frequently Columns must be listed explicitly Views must be created with the SCHEMABINDING option Allows the data in a large table to be split into smaller member tables. Data can be partitioned between the member tables based on ranges of data values. Partitioned Views make it easier to maintain the member tables independently. Allows the data in a large table to be split into smaller member tables. Data can be partitioned between the member tables based on ranges of data values. Partitioned Views make it easier to maintain the member tables independently. Partitioned View Details A partitioned view joins horizontally partitioned data from a set of member tables across one or more servers, making the data appear as if from one table.

Creating a Partitioned View Partitioned View Example CREATE TABLE May1998sales (OrderID INT, CustomerID INT NOT NULL, OrderDate DATETIME NULL CHECK (DATEPART(yy, OrderDate) = 1998), OrderMonth INT CHECK (OrderMonth = 5), DeliveryDate DATETIME NULL CONSTRAINT OrderIDMonth PRIMARY KEY(OrderID, OrderMonth) ) CREATE TABLE May1998sales (OrderID INT, CustomerID INT NOT NULL, OrderDate DATETIME NULL CHECK (DATEPART(yy, OrderDate) = 1998), OrderMonth INT CHECK (OrderMonth = 5), DeliveryDate DATETIME NULL CONSTRAINT OrderIDMonth PRIMARY KEY(OrderID, OrderMonth) ) CREATE VIEW Year1998Sales AS SELECT * FROM Jan1998Sales UNION ALL SELECT * FROM Feb1998Sales UNION ALL SELECT * FROM Mar1998Sales UNION ALL SELECT * FROM Apr1998Sales UNION ALL SELECT * FROM May1998Sales UNION ALL SELECT * FROM Jun1998Sales UNION ALL SELECT * FROM Jul1998Sales UNION ALL … CREATE VIEW Year1998Sales AS SELECT * FROM Jan1998Sales UNION ALL SELECT * FROM Feb1998Sales UNION ALL SELECT * FROM Mar1998Sales UNION ALL SELECT * FROM Apr1998Sales UNION ALL SELECT * FROM May1998Sales UNION ALL SELECT * FROM Jun1998Sales UNION ALL SELECT * FROM Jul1998Sales UNION ALL …

Demonstration: Building a View In this demonstration, you will see how to: Create a view Query a view Generate a script for a view

Lesson 2: Overview of User-Defined Functions What Are User-Defined Functions? Creating and Managing User-Defined Functions Creating a Table Valued User-Defined Function Restrictions When Creating User-Defined Functions How to Implement Different Types of User-Defined Functions Performance Considerations for Using User-Defined Functions

What Are User-Defined Functions? Modular programming for reusable logic. Complex operations can be optimized for faster execution. Logic performed in database reduces network traffic Modular programming for reusable logic. Complex operations can be optimized for faster execution. Logic performed in database reduces network traffic Benefits of using User-Defined Functions A User-Defined Function is a routine that accepts parameters, performs an action, and returns the result of that action as a value.

Creating and Managing User-Defined Functions Creating or Modifying a User-Defined Function [CREATE|ALTER] FUNCTION int) RETURNS varchar(50) AS BEGIN varchar(50) = Address FROM HumanResources.Employee WHERE EmployeeID END [CREATE|ALTER] FUNCTION int) RETURNS varchar(50) AS BEGIN varchar(50) = Address FROM HumanResources.Employee WHERE EmployeeID END Deleting a view DROP FUNCTION fEmployee

Creating a Table Valued User-Defined Function CREATE FUNCTION nchar(1)) RETURNS table AS BEGIN RETURN (SELECT * FROM HumanResources.Employee WHERE Gender END CREATE FUNCTION nchar(1)) RETURNS table AS BEGIN RETURN (SELECT * FROM HumanResources.Employee WHERE Gender END Querying a Table Valued User-Defined Function SELECT * FROM fEmployeeByGender(‘F’)

Restrictions When Creating User-Defined Functions You cannot use user-defined functions to: Update data Use stored procedures instead Update data Use stored procedures instead Define or create new objects in the database Objects referred to by the function have to be previously declared and created Define or create new objects in the database Objects referred to by the function have to be previously declared and created Perform transactions

How To Implement Different Types Of User- Defined Functions TypesUsage Scalar-valued Scalar is specified in the RETURNS clause Can be defined with multiple T-SQL statements Inline table-valued TABLE is specified in the RETURNS clause Does not have associated return variables select_stmt is the single SELECT statement that defines the return value Multi-statement table-valued TABLE is specified in the RETURNS clause function_body is used as a series of T-SQL statements that populate a TABLE return is used to store and accumulate rows that are returned as the value

Performance Considerations For Using User- Defined Functions Both functions will be called once for each row in the table. If both functions require 0.1 second for each execution, the query will require: 1 second for 5 rows 10 seconds for 50 rows 1 hour for 18,000 rows Both functions will be called once for each row in the table. If both functions require 0.1 second for each execution, the query will require: 1 second for 5 rows 10 seconds for 50 rows 1 hour for 18,000 rows SELECT MyCalculation(column_name) FROM table_name WHERE MyCondition(column_name) SELECT MyCalculation(column_name) FROM table_name WHERE MyCondition(column_name)

Demonstration: Building a User-Defined Function In this demonstration, you will see how to: Create a user-defined function Call a user-defined function

Lesson 3: Overview of Stored Procedures What Are Stored Procedures? How Are Stored Procedures Created? Stored Procedure Initial Execution Stored Procedure Practices

What Are Stored Procedures? Accept input parameters Return output parameters or rowset Return a status value to indicate success or failure Accept input parameters Return output parameters or rowset Return a status value to indicate success or failure Promotes modular programming Provides security attributes and permission chaining Allows delayed binding and code reuse Reduces network traffic Promotes modular programming Provides security attributes and permission chaining Allows delayed binding and code reuse Reduces network traffic Stored Procedures Can: Benefits of using Stored Procedures: A collection of T-SQL statements stored on the server

How Are Stored Procedures Created? CREATE PROCEDURE char(1) AS BEGIN SELECT BusinessEntityID, FirstName, LastName, Address FROM HumanResources.vEmployee WHERE FirstName + '%' ORDER BY FirstName END CREATE PROCEDURE char(1) AS BEGIN SELECT BusinessEntityID, FirstName, LastName, Address FROM HumanResources.vEmployee WHERE FirstName + '%' ORDER BY FirstName END EXECUTE HumanResources.usp_GetEmployeesName 'A‘ Creating a Stored Procedure Calling a Stored Procedure

Stored Procedure Initial Execution SQL Server® query optimizer builds an execution plan for stored procedures on initial execution Compiled execution plans are stored in the stored procedure cache for future use Initial Execution Phases Parsing Resolving Optimizing Compiling Executing Parsing Resolving Optimizing Compiling Executing Use of WITH RECOMPILE in CREATE PROCEDURE Schema changes to referenced objects Running sp_recompile Use of WITH RECOMPILE in CREATE PROCEDURE Schema changes to referenced objects Running sp_recompile Recompile Can Be Caused By

Stored Procedure Best Practices Use WITH ENCRYPTION to hide procedure source Use WITH RECOMPILE to force recompilation on each execution Use WITH ENCRYPTION to hide procedure source Use WITH RECOMPILE to force recompilation on each execution Validate all input parameters Avoid building string based SQL within procedure to reduce the risk of SQL injection Use cursors sparingly Validate all input parameters Avoid building string based SQL within procedure to reduce the risk of SQL injection Use cursors sparingly Stored Procedure Tips Stored Procedure Best Practices

Demonstration: Creating Stored Procedures In this demonstration, you will see how to: Create a stored procedure Call a stored procedure

Lesson 4: Overview of Triggers What Are Triggers? How Are Triggers Created? How Triggers Work Trigger Types and Limitations

What Are Triggers? A special type of stored procedure that executes when an attempt is made to modify data in a table Typically used to maintain low-level data integrity and not used to return query results Two categories of DML triggers: INSTEAD OF and AFTER. INSTEAD OF trigger is also known as the BEFORE trigger A collection of T-SQL statements stored on the server that Evaluates data before or after it is inserted, modified, or Deleted.

How Are Triggers Created? CREATE TRIGGER Sales.trigCurrency ON Sales.Currency AFTER INSERT AS BEGIN nvarchar(50) = Name FROM inserted IF < 5 BEGIN ROLLBACK TRANSACTION END CREATE TRIGGER Sales.trigCurrency ON Sales.Currency AFTER INSERT AS BEGIN nvarchar(50) = Name FROM inserted IF < 5 BEGIN ROLLBACK TRANSACTION END Creating a Trigger

How Triggers Work Triggers can roll back transactions if a specific business rule is not satisfied When a trigger that contains a rollback statement is executed from an SQL batch, the entire batch is canceled Any statement following the ROLLBACK TRANSACTION statement will still be executed Any modifications that happen after the rollback are not rolled back

Trigger Types and Limitations Command is issued Data is modified Command is complete Insert, Update, or Delete Statement INSTEAD OF Trigger AFTER Trigger A trigger can apply to only one table Triggers are executed only in the current database Triggers must belong to the same schema as their target table INSTEAD OF DELETE/UPDATE triggers cannot be created on a table that has a cascading foreign key defined. A trigger can apply to only one table Triggers are executed only in the current database Triggers must belong to the same schema as their target table INSTEAD OF DELETE/UPDATE triggers cannot be created on a table that has a cascading foreign key defined. Trigger Limitations

Demonstration: Creating Triggers In this demonstration, you will see how to: Create a trigger See the results of a trigger

Lesson 5: Writing Distributed Queries How SQL Server Works with Heterogeneous Data Adding Linked Servers Using Ad Hoc Distributed Queries How to Write Linked Server-Based Distributed Queries

How SQL Server Works with Heterogeneous Data SQL Server IBM DB2 Linked as: Sales Oracle Linked as: Marketing Linked Servers SELECT ID, SendDate FROM Marketing.Catalogs.dbo.History SELECT ID, SendDate FROM Marketing.Catalogs.dbo.History Distributed Queries from SQL Server® to Other Systems

Adding Linked Servers Add a Linked Server  Other Databases  Files  Non-Relational Data Sources Use AdventureWorks ; GO EXEC = = = = ‘OraServer' Use AdventureWorks ; GO EXEC = = = = ‘OraServer' Use AdventureWorks ; GO EXEC = = = = = 'd89q3w4u' Use AdventureWorks ; GO EXEC = = = = = 'd89q3w4u' Map Credentials  Associate with linked server  Specify local login  Map to remote login

Using Ad Hoc Distributed Queries Accesses remote heterogeneous data Best if the remote data does not need to be accessed often A permanent link is not required for better security Accesses remote heterogeneous data Best if the remote data does not need to be accessed often A permanent link is not required for better security SELECT ID, SendDate FROM OPENROWSET(‘MSDAORA’, ‘OraServer’, ‘MaryP’, ‘d89q3w4u’, ‘SELECT * FROM Catalog.dbo.History’) SELECT ID, SendDate FROM OPENROWSET(‘MSDAORA’, ‘OraServer’, ‘MaryP’, ‘d89q3w4u’, ‘SELECT * FROM Catalog.dbo.History’) SELECT ID, SendDate FROM OPENDATASOURCE(‘MSDAORA’, ‘Data Source=OraServer; User=MaryP; Password=d89q3w4u’).Catalog.dbo.History’ SELECT ID, SendDate FROM OPENDATASOURCE(‘MSDAORA’, ‘Data Source=OraServer; User=MaryP; Password=d89q3w4u’).Catalog.dbo.History’

How to Write Linked Server-Based Distributed Queries Use a fully qualified four-part name and the OPENQUERY function The OPENQUERY function executes the query on the specified linked server SELECT * FROM OPENQUERY(OracleSvr, 'SELECT name, id FROM HumanResources.Titles') SELECT * FROM OPENQUERY(OracleSvr, 'SELECT name, id FROM HumanResources.Titles')

Lab: Using Programming Objects for Data Retrieval Exercise 1: Creating Views Exercise 2: Creating User-Defined Functions Exercise 3: Creating Stored Procedures Exercise 4: Writing Distributed Queries Logon information Virtual machineNY-SQL-01 User nameAdministrator Password Pa$$w0rd Estimated time: 60 minutes

Lab Scenario You are the database administrator at Adventure Works. You need to create several user-defined functions to meet the custom requirements of your organization. You will create a scalar user-defined function that removes the time part from the datetime() object and present only the date related information. Yet another user-defined function retrieves details about purchase orders of a particular vendor when supplied with a VendorID. After this, you will create views which present a simplified version of tables with only the relevant columns from the AdventureWorks database. You will also create a stored procedure that can be used to query the view that you created. Then, you will execute an ad hoc distributed query against data in a Microsoft Office Excel spreadsheet. Finally you will create a linked server to that spreadsheet and query the linked server.

Lab Review What is the difference between scalar and table type user- defined functions? Why would a linked server be used instead of an ad hoc distributed query? How is a table type user-defined function queried? Where are stored procedure execution plans stored after initial execution?

Module Review and Takeaways Review Questions