Presentation is loading. Please wait.

Presentation is loading. Please wait.

Using Table Expressions

Similar presentations


Presentation on theme: "Using Table Expressions"— Presentation transcript:

1 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

2 20761B Module Overview 11: Using Table Expressions Using CTEs

3 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>;

4 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;

5 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 B or the SQL Server 2016 Technical Documentation: Table-Valued Functions 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.

6 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 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 INT) RETURNS TABLE AS RETURN SELECT orderid, CAST((qty * unitprice * (1 - discount)) AS DECIMAL(8, 2)) AS line_total FROM Sales.OrderDetails WHERE orderid ;

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

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

9 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>;

10 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

11 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;

12 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. INT = 9; SELECT orderyear, COUNT(DISTINCT custid) AS cust_count FROM ( SELECT YEAR(orderdate) AS orderyear, custid FROM Sales.Orders WHERE ) AS derived_year GROUP BY orderyear;

13 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;

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

15 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>;

16 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;


Download ppt "Using Table Expressions"

Similar presentations


Ads by Google