+ All Categories
Home > Documents > 2778A_08

2778A_08

Date post: 05-Apr-2018
Category:
Upload: rodrigo-pena
View: 223 times
Download: 0 times
Share this document with a friend

of 41

Transcript
  • 7/31/2019 2778A_08

    1/41

    Module 8:

    Using ProgrammingObjects for Data Retrieval

  • 7/31/2019 2778A_08

    2/41

  • 7/31/2019 2778A_08

    3/41

    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

  • 7/31/2019 2778A_08

    4/41

    What Are Views?

    Employee (table)

    EmployeeID LastName FirstName Title

    287 Mensa-Annan Tete Mr.

    288 Abbas Syed Mr.

    289 Valdez Rachel NULL

    vEmployee (view)

    LastName FirstName

    Mensa-Annan Tete

    Abbas Syed

    Valdez Rachel

    A View is a stored query producing a virtual table

  • 7/31/2019 2778A_08

    5/41

    Creating or Modifying a view

    Creating and Managing a View

    [CREATE|ALTER] VIEWHumanResources.vEmployeeASBEGIN

    SELECT EmployeeID, FirstName, LastName,

    EmailAddressFROM HumanResources.Employee

    END

    Deleting a view

    DROP VIEWHumanResources.vEmployee

  • 7/31/2019 2778A_08

    6/41

    Considerations When Creating Views

    Restriction Description

    Column Limit Total number of columns referenced in the viewcannot 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

  • 7/31/2019 2778A_08

    7/41

    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 DISTINCTclauses.

    Data must follow the restrictions on the modified columns

    Statements must modify columns from only one basetable

    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:

  • 7/31/2019 2778A_08

    8/41

    Indexed Views

    Views can be indexed using CREATE INDEX

    Should not be used for views whose underlying data isupdated frequentlyColumns must be listed explicitlyViews must be created with the SCHEMABINDING option

    Views can be indexed using CREATE INDEX

    Should not be used for views whose underlying data isupdated 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 indexhas been created.

  • 7/31/2019 2778A_08

    9/41

    Creating an Indexed View

    Indexed View Example

    CREATE VIEWvwDiscountWITH SCHEMABINDING AS

    SELECT SUM(UnitPrice*OrderQty)AS SumPrice,SUM(UnitPrice*OrderQty*(1.00-UnitPriceDiscount))ASSumDiscountPrice,

    SUM(UnitPrice*OrderQty*UnitPriceDiscount)ASSumDiscountPrice2,COUNT_BIG(*) AS Count, ProductIDFROMSales.SalesOrderDetailGROUP BY ProductID

    GO

    CREATE UNIQUE CLUSTERED INDEXvwDiscountInd ON vwDiscount(ProductID)

  • 7/31/2019 2778A_08

    10/41

    Partitioned Views

    Views can be indexed using CREATE INDEX

    Should not be used for views whose underlying data isupdated frequentlyColumns must be listed explicitlyViews must be created with the SCHEMABINDING option

    Allows the data in a large table to be split into smallermember tables.

    Data can be partitioned between the member tablesbased on ranges of data values.

    Partitioned Views make it easier to maintain the membertables independently.

    Partitioned View Details

    A partitioned view joins horizontally partitioned data from aset of member tables across one or more servers, making thedata appear as if from one table.

  • 7/31/2019 2778A_08

    11/41

    Creating a Partitioned View

    Partitioned View Example

    CREATE TABLE May1998sales(OrderID INT,CustomerID INT NOT NULL,OrderDate DATETIME NULLCHECK(DATEPART(yy,OrderDate) = 1998),OrderMonth INTCHECK(OrderMonth = 5),DeliveryDate DATETIME NULLCONSTRAINT OrderIDMonthPRIMARY KEY(OrderID,OrderMonth))

    CREATE VIEWYear1998SalesASSELECT * FROM Jan1998SalesUNION ALLSELECT * FROM Feb1998SalesUNION ALL

    SELECT * FROM Mar1998SalesUNION ALLSELECT * FROM Apr1998SalesUNION ALLSELECT * FROM May1998SalesUNION ALLSELECT * FROM Jun1998Sales

    UNION ALLSELECT * FROM Jul1998SalesUNION ALL

  • 7/31/2019 2778A_08

    12/41

    Demonstration: Building a View

    In this demonstration, you will see how to:

    Create a view

    Query a view

    Generate a script for a view

  • 7/31/2019 2778A_08

    13/41

    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-DefinedFunctions

    Performance Considerations for Using User-DefinedFunctions

  • 7/31/2019 2778A_08

    14/41

    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

    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 avalue.

  • 7/31/2019 2778A_08

    15/41

    Creating and Managing User-Defined Functions

    Creating or Modifying a User-Defined Function

    [CREATE|ALTER] FUNCTION fEmployeeEmail(@ID int)RETURNS varchar(50)

    ASBEGINDECLARE @email varchar(50)

    SELECT @email = EmailAddressFROM HumanResources.EmployeeWHERE EmployeeID = @ID

    RETURN @email

    END

    Deleting a view

    DROP FUNCTION fEmployeeEmail

  • 7/31/2019 2778A_08

    16/41

    Creating a Table Valued User-Defined Function

    Creating a Table Valued User-Defined Function

    CREATE FUNCTION fEmployeeByGender(@Gender nchar(1))RETURNStableASBEGIN

    RETURN (SELECT *FROM HumanResources.EmployeeWHERE Gender = @Gender)

    END

    Querying a Table Valued User-Defined Function

    SELECT * FROMfEmployeeByGender(F)

    R t i ti Wh C ti U D fi d

  • 7/31/2019 2778A_08

    17/41

    Restrictions When Creating User-DefinedFunctions

    You cannot use user-defined functions to:

    Update data

    Use stored procedures instead

    Define or create new objects in the database

    Objects referred to by the function have to bepreviously declared and created

    Perform transactions

  • 7/31/2019 2778A_08

    18/41

    P f C id ti F U i U

  • 7/31/2019 2778A_08

    19/41

    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, thequery will require:

    1 second for 5 rows

    10 seconds for 50 rows

    1 hour for 18,000 rows

    SELECTMyCalculation(column_name)FROM table_nameWHEREMyCondition(column_name)

  • 7/31/2019 2778A_08

    20/41

    Demonstration: Building a User-Defined Function

    In this demonstration, you will see how to:

    Create a user-defined function

    Call a user-defined function

  • 7/31/2019 2778A_08

    21/41

    Lesson 3: Overview of Stored Procedures

    What Are Stored Procedures?

    How Are Stored Procedures Created?

    Stored Procedure Initial Execution

    Stored Procedure Practices

  • 7/31/2019 2778A_08

    22/41

    What Are Stored Procedures?

    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

    Stored Procedures Can:

    Benefits of using Stored Procedures:

    A collection of T-SQL statements stored on the server

  • 7/31/2019 2778A_08

    23/41

    How Are Stored Procedures Created?

    CREATE PROCEDURE HumanResources.usp_GetEmployeesName@NamePrefix char(1)

    ASBEGINSELECT BusinessEntityID, FirstName, LastName,

    EmailAddressFROM HumanResources.vEmployeeWHERE FirstName LIKE @NamePrefix + '%'ORDER BY FirstNameEND

    EXECUTEHumanResources.usp_GetEmployeesName 'A

    Creating a Stored Procedure

    Calling a Stored Procedure

  • 7/31/2019 2778A_08

    24/41

    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 storedprocedure cache for future use

    Initial Execution Phases

    Parsing

    Resolving

    Optimizing

    Compiling

    Executing

    Use of WITH RECOMPILE inCREATE PROCEDURE

    Schema changes toreferenced objects

    Running sp_recompile

    Recompile Can Be Caused By

  • 7/31/2019 2778A_08

    25/41

    Stored Procedure Best Practices

    Use WITH ENCRYPTION to hide procedure source

    Use WITH RECOMPILE to force recompilation on eachexecution

    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

  • 7/31/2019 2778A_08

    26/41

    Demonstration: Creating Stored Procedures

    In this demonstration, you will see how to:

    Create a stored procedure

    Call a stored procedure

  • 7/31/2019 2778A_08

    27/41

    Lesson 4: Overview of Triggers

    What Are Triggers?

    How Are Triggers Created?

    How Triggers Work

    Trigger Types and Limitations

  • 7/31/2019 2778A_08

    28/41

    What Are Triggers?

    A special type of stored procedure that executes when anattempt is made to modify data in a table

    Typically used to maintain low-level data integrity and notused 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, orDeleted.

  • 7/31/2019 2778A_08

    29/41

    How Are Triggers Created?

    CREATE TRIGGERSales.trigCurrencyON Sales.CurrencyAFTER INSERT

    AS

    BEGINDECLARE @name nvarchar(50)SELECT @name = NameFROM insertedIF len(@name) < 5BEGIN

    ROLLBACK TRANSACTIONEND

    END

    Creating a Trigger

  • 7/31/2019 2778A_08

    30/41

    How Triggers Work

    Triggers can roll back transactions if a specific business ruleis not satisfied

    When a trigger that contains a rollback statement isexecuted from an SQL batch, the entire batch is canceled

    Any statement following the ROLLBACK TRANSACTIONstatement will still be executed

    Any modifications that happen after the rollback are notrolled back

  • 7/31/2019 2778A_08

    31/41

    Trigger Types and Limitations

    Command isissued

    Data ismodified

    Command iscomplete

    Insert, Update, or Delete Statement

    INSTEAD OFTrigger

    AFTERTrigger

    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 targettable

    INSTEAD OF DELETE/UPDATE triggers cannot be created ona table that has a cascading foreign key defined.

    Trigger Limitations

  • 7/31/2019 2778A_08

    32/41

    Demonstration: Creating Triggers

    In this demonstration, you will see how to:

    Create a trigger

    See the results of a trigger

  • 7/31/2019 2778A_08

    33/41

    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

  • 7/31/2019 2778A_08

    34/41

    How SQL Server Works with Heterogeneous Data

    SQL Server

    IBM DB2Linked as: Sales

    OracleLinked as: Marketing

    Linked Servers

    SELECT ID, SendDateFROMMarketing.Catalogs.dbo.History

    Distributed Queries from SQL Server to Other Systems

  • 7/31/2019 2778A_08

    35/41

    Adding Linked Servers

    Add a Linked Server

    Other Databases

    Files

    Non-Relational DataSources

    Use AdventureWorks ;GO

    EXEC sp_addlinkedserver@server = Marketing',

    @srvproduct = 'Oracle',

    @provider = 'MSDAORA',

    @datasrc = OraServer'

    Use AdventureWorks ;GO

    EXEC sp_addlinkedsrvlogin

    @rmtsrvname = Marketing',

    @useself = 'false',@locallogin = 'Mary',

    @rmtuser = 'MaryP',

    @rmtpassword = 'd89q3w4u'

    Map Credentials

    Associate with

    linked server Specify local login

    Map to remote login

  • 7/31/2019 2778A_08

    36/41

    Using Ad Hoc Distributed Queries

    Accesses remote heterogeneous data

    Best if the remote data does not need to be accessedoften

    A permanent link is not required for better security

    SELECT ID, SendDateFROM OPENROWSET(MSDAORA, OraServer, MaryP,d89q3w4u, SELECT * FROM Catalog.dbo.History)

    SELECT ID, SendDateFROM OPENDATASOURCE(MSDAORA,Data Source=OraServer; User=MaryP;Password=d89q3w4u).Catalog.dbo.History

    How to Write Linked Server-Based Distributed

  • 7/31/2019 2778A_08

    37/41

    How to Write Linked Server Based DistributedQueries

    Use a fully qualified four-part name and the OPENQUERYfunction

    The OPENQUERY function executes the query on thespecified linked server

    SELECT *FROM OPENQUERY(OracleSvr, 'SELECT name, id FROMHumanResources.Titles')

    Lab: Using Programming Objects for Data

  • 7/31/2019 2778A_08

    38/41

    Lab: Using Programming Objects for DataRetrieval

    Exercise 1: Creating Views

    Exercise 2: Creating User-Defined Functions

    Exercise 3: Creating Stored Procedures

    Exercise 4: Writing Distributed Queries

    Logon information

    Virtual machine NY-SQL-01

    User name Administrator

    Password Pa$$w0rd

    Estimated time: 60 minutes

  • 7/31/2019 2778A_08

    39/41

    Lab Scenario

    You are the database administrator at Adventure Works. Youneed to create several user-defined functions to meet the

    custom requirements of your organization. You will create ascalar user-defined function that removes the time part fromthe datetime() object and present only the date relatedinformation. Yet another user-defined function retrievesdetails about purchase orders of a particular vendor whensupplied with a VendorID.

    After this, you will create views which present a simplifiedversion of tables with only the relevant columns from theAdventureWorks database. You will also create a storedprocedure that can be used to query the view that youcreated. Then, you will execute an ad hoc distributed query

    against data in a Microsoft Office Excel spreadsheet. Finallyyou will create a linked server to that spreadsheet and querythe linked server.

  • 7/31/2019 2778A_08

    40/41

    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 hocdistributed query?

    How is a table type user-defined function queried?

    Where are stored procedure execution plans stored afterinitial execution?

  • 7/31/2019 2778A_08

    41/41

    Module Review and Takeaways

    Review Questions