Using Table Expressions

Slides:



Advertisements
Similar presentations
02 | Advanced SELECT Statements Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager.
Advertisements

2.2 SQL Server 2005 的 XML 支援功能. Overview XML Enhancements in SQL Server 2005 The xml Data Type Using XQuery.
Introduction to Databases Chapter 8: Improving Data Access.
Database Design for DNN Developers Sebastian Leupold.
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.
Introduction to Databases Chapter 7: Data Access and Manipulation.
Module 7 Reading SQL Server® 2008 R2 Execution Plans.
Module 8: Implementing Stored Procedures. Introducing Stored Procedures Creating, Modifying, Dropping, and Executing Stored Procedures Using Parameters.
Module 9 Designing and Implementing Stored Procedures.
Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall 1 Modern Database Management 11 th Edition Jeffrey A. Hoffer, V. Ramesh, Heikki Topi.
1 Definition of a subquery Nested subqueries Correlated subqueries The ISNULL function Derived tables The EXISTS operator Mixing data types: CAST & CONVERT.
04 | Grouping and Aggregating Data Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager.
Module 18 Querying XML Data in SQL Server® 2008 R2.
Improving Database Performance Derrick Rapley
Module 4 Designing and Implementing Views. Module Overview Introduction to Views Creating and Managing Views Performance Considerations for Views.
Chapter 15 Introduction to PL/SQL. Chapter Objectives  Explain the benefits of using PL/SQL blocks versus several SQL statements  Identify the sections.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
Module 11 Authorizing Users to Access Resources. Module Overview Authorizing User Access to Objects Authorizing Users to Execute Code Configuring Permissions.
SQL Server 2012 Session: 1 Session: 12 Triggers Data Management Using Microsoft SQL Server.
Module 3: Using XML. Overview Retrieving XML by Using FOR XML Shredding XML by Using OPENXML Introducing XQuery Using the xml Data Type.
LINQ to DATABASE-2.  Creating the BooksDataContext  The code combines data from the three tables in the Books database and displays the relationships.
Stored Procedures / Session 4/ 1 of 41 Session 4 Module 7: Introducing stored procedures Module 8: More about stored procedures.
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.
SQL Triggers, Functions & Stored Procedures Programming Operations.
 CONACT UC:  Magnific training   
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.
Views / Session 3/ 1 of 40 Session 3 Module 5: Implementing Views Module 6: Managing Views.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
Managing, Storing, and Executing DTS Packages
A Guide to SQL, Seventh Edition
Implementing Views Advanced Database Dr. AlaaEddin Almabhouh.
Dynamic SQL Writing Efficient Queries on the Fly
Data Virtualization Demoette… Data Lineage Reporting
02 | Advanced SELECT Statements
Sorting and Filtering Data
Dynamic SQL: Writing Efficient Queries on the Fly
Querying Multiple Tables
09 | Modifying Data Graeme Malcolm | Senior Content Developer, Microsoft Geoff Allix | Principal Technologist, Content Master.
20761A 10: Using Subqueries Module 10   Using Subqueries.
Data Virtualization Tutorial: JSON_TABLE Queries
Module 7: Implementing Views
Dynamic SQL Writing Efficient Queries on the Fly
20761A 11: Using Set Operators Module 11   Using Set Operators.
Using Window Ranking, Offset, and Aggregate Functions
Sorting and Filtering Data
Introduction to T-SQL Querying
Querying Multiple Tables
06 | Using Subqueries and APPLY
20761B 12: Using Set Operators Module 12   Using Set Operators.
09 | Modifying Data Graeme Malcolm | Senior Content Developer, Microsoft Geoff Allix | Principal Technologist, Content Master.
පාඨමාලා මාතෘකා Microsoft SQL Server Databases සැකසීම
Writing SELECT Queries
07 | Using Table Expressions
20761B 10: Using Subqueries Module 10   Using Subqueries.
Dynamic SQL: Writing Efficient Queries on the Fly
LINQ to DATABASE-2.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
Microsoft SQL Server 2014 for Oracle DBAs Module 7
Chapter 2 Views.
Contents Preface I Introduction Lesson Objectives I-2
Chapter 8 Advanced SQL.
IST 318 Database Administration
Improving the Performance of Functions
Grouping and Aggregating Data
Introduction to T-SQL Querying
Presentation transcript:

Using Table Expressions Module 11 Note: while the handling of user objects such as views and inline table-valued functions will be included, their creation will only be covered at a very high level, leaving a thorough treatment for course 20764B. Using Table Expressions

20761B Module Overview 11: Using Table Expressions Using CTEs  

Writing Queries That Return Results from Views 20761B Writing Queries That Return Results from Views 11: Using Table Expressions Views may be referenced in a SELECT statement just like a table Views are named table expressions with definitions stored in a database Like derived tables and CTEs, queries that use views can provide encapsulation and simplification From an administrative perspective, views can provide a security layer to a database   SELECT <select_list> FROM <view_name> ORDER BY <sort_list>;

20761B Creating Simple Views 11: Using Table Expressions Views are saved queries created in a database by administrators and developers Views are defined with a single SELECT statement ORDER BY is not permitted in a view definition without the use of TOP, OFFSET/FETCH, or FOR XML To sort the output, use ORDER BY in the outer query View creation supports additional options beyond the scope of this class Note that column aliases, encryption and schema binding in a view definition are beyond the scope of this class. This lesson covers the basics of creating views for the purposes of discussion about querying them only. For more information on views and view options, see course 20762B: Developing Microsoft SQL Server Databases. Keep this discussion very high level. CREATE VIEW HR.EmpPhoneList AS SELECT empid, lastname, firstname, phone FROM HR.Employees;

Writing Queries That Use Inline TVFs 20761B Writing Queries That Use Inline TVFs 11: Using Table Expressions TVFs are named table expressions with definitions stored in a database TVFs return a virtual table to the calling query SQL Server provides two types of TVFs: Inline, based on a single SELECT statement Multi-statement, which creates and loads a table variable Unlike views, TVFs support input parameters Inline TVFs may be thought of as parameterized views Note that multi-statement TVFs are beyond the scope of this course. For more information, see course 20764B or the SQL Server 2016 Technical Documentation: Table-Valued Functions http://go.microsoft.com/fwlink/?LinkID=394806 Note: many dynamic management views (DMVs) are actually dynamic management functions (DMFs). Since students are likely to need to do metadata and system catalog querying, there is good justification for including the use of TVFs at this point.

Creating Simple Inline TVFs 20761B Creating Simple Inline TVFs 11: Using Table Expressions TVFs are created by administrators and developers Create and name function and optional parameters with CREATE FUNCTION Declare return type as TABLE Define inline SELECT statement following RETURN This content is included to comply with the objective domain for the course. Refer to course 10776 for more information. Though the use of GO was omitted for clarity, remember that CREATE FUNCTION (like CREATE VIEW) must be the only statement in the batch. CREATE FUNCTION Sales.fn_LineTotal (@orderid INT) RETURNS TABLE AS RETURN SELECT orderid, CAST((qty * unitprice * (1 - discount)) AS DECIMAL(8, 2)) AS line_total FROM Sales.OrderDetails WHERE orderid = @orderid ;

Retrieving from Inline TVFs 20761B Retrieving from Inline TVFs 11: Using Table Expressions SELECT from function Use two-part name Pass in parameters Note: point out to students that it is a best practice to assign a table alias to the TVF, even though it is not required. SELECT orderid, line_total FROM Sales.fn_LineTotal(10252) AS LT; orderid line_total 10252 2462.40 47.50 1088.00

Lesson 3: Using Derived Tables 11: Using Table Expressions Demonstration: Using Derived Tables Note that this lesson discusses using variables to pass arguments to derived tables before the course itself covers variables. Provide "just enough" information on variables to support their use, and let the students know this will be covered thoroughly later in the course. Question You are troubleshooting the following query, which returns an error: SELECT orderyear, COUNT(DISTINCT custid) AS cust_count FROM ( SELECT YEAR(orderdate) AS orderyear, custid FROM Sales.Orders WHERE empid = 354 ORDER BY YEAR(orderdate) ) AS derived_year GROUP BY orderyear; How can you resolve the error? Answer Remove the ORDER BY clause from the derive table query.

Writing Queries with Derived Tables 11: Using Table Expressions Derived tables are named query expressions created within an outer SELECT statement Not stored in database—represents a virtual relational table When processed, unpacked into query against underlying referenced objects Allow you to write more modular queries Scope of a derived table is the query in which it is defined Note that derived tables allow a query to work around T-SQL restrictions on the use of column aliases in query phases that logically execute before the SELECT clause. Point out that the lifetime of the derived table is the outer query. When the outer query finishes, the derived table no longer exists. Because the derived table definition is unpacked and processed at runtime against the underlying objects, there are no performance benefits nor specific performance costs to using them. SELECT <column_list> FROM ( <derived_table_definition> ) AS <derived_table_alias>;

Guidelines for Derived Tables 11: Using Table Expressions Derived Tables Must Derived Tables May   Have an alias Have names for all columns Have unique names for all columns Not use an ORDER BY clause (without TOP or OFFSET/FETCH) Not be referred to multiple times in the same query Use internal or external aliases for columns Refer to parameters and/or variables Be nested within other derived tables

Using Aliases for Column Names in Derived Tables 11: Using Table Expressions Column aliases may be defined inline: Column aliases may be defined externally: SELECT orderyear, COUNT(DISTINCT custid) AS cust_count FROM ( SELECT YEAR(orderdate) AS orderyear, custid FROM Sales.Orders) AS derived_year GROUP BY orderyear; This example uses the same query logic (return the number of distinct customers per year) to contrast the use of internal and external column aliases. Note that the outer query refers to columns defined in the inner derived table. In the first example, the aliases are defined inline in the SELECT clause. In the second example, the columns are defined externally to the SELECT statement, with the derived table's alias. Point out that the external method may cause testing and code maintenance issues. SELECT orderyear, COUNT(DISTINCT custid) AS cust_count FROM ( SELECT YEAR(orderdate), custid FROM Sales.Orders) AS derived_year(orderyear, custid) GROUP BY orderyear;

Passing Arguments to Derived Tables 11: Using Table Expressions Derived tables may refer to arguments Arguments might be: Variables declared in the same batch as the SELECT statement Parameters passed into a table-valued function or stored procedure Note that the use of variables and parameters will be covered more thoroughly later in this course. DECLARE @emp_id INT = 9; SELECT orderyear, COUNT(DISTINCT custid) AS cust_count FROM ( SELECT YEAR(orderdate) AS orderyear, custid FROM Sales.Orders WHERE empid=@emp_id ) AS derived_year GROUP BY orderyear;

Nesting and Reusing Derived Tables 11: Using Table Expressions Derived tables may be nested, though not recommended: Derived tables may not be referred to multiple times in the same query Each reference must be separately defined Note: One possible answer to the question: “How could you rewrite the previous example to eliminate one level of nesting?” is provided in the demonstration script. SELECT orderyear, cust_count FROM ( SELECT orderyear, COUNT(DISTINCT custid) AS cust_count FROM ( SELECT YEAR(orderdate) AS orderyear ,custid FROM Sales.Orders) AS derived_table_1 GROUP BY orderyear) AS derived_table_2 WHERE cust_count > 80;

Demonstration: Using CTEs 20761B Lesson 4: Using CTEs 11: Using Table Expressions Demonstration: Using CTEs Question Which of the following features is required for a CTE query? ( )Option 1: The query must have a WITH … AS clause. ( )Option 2: The query must include a GROUP BY clause. ( )Option 3: The query must include a CREATE FUNCTION statement. ( )Option 4: The query must include a nested derived query. Answer (√) Option -2: The query must have a WITH … AS clause.

Writing Queries with CTEs 20761B Writing Queries with CTEs 11: Using Table Expressions CTEs are named table expressions defined in a query CTEs are similar to derived tables in scope and naming requirements Unlike derived tables, CTEs support multiple definitions, multiple references, and recursion Since a CTE is defined before it is used, it may be referred to more flexibly than a derived table. Note that creating recursive CTEs is beyond the scope of the class. To support questions that may come up, an example of a recursive CTE is included in the demonstration script for this lesson. WITH <CTE_name> AS ( <CTE_definition> ) <outer query referencing CTE>;

Creating Queries with Common Table Expressions 11: Using Table Expressions To create a CTE: Define the table expression in a WITH clause Assign column aliases (inline or external) Pass arguments if desired Reference the CTE in the outer query This example uses the same logical query (return the number of distinct customers per year) as the derived table example in the previous lesson. WITH CTE_year AS ( SELECT YEAR(orderdate) AS orderyear, custid FROM Sales.Orders ) SELECT orderyear, COUNT(DISTINCT custid) AS cust_count FROM CTE_year GROUP BY orderyear;