What are Common Table Expressions?
A common table expression (CTE) can be thought of as a temporary result set that is defined within the execution scope of a single SELECT, INSERT, UPDATE, DELETE, or CREATE VIEW statement. A CTE is similar to a derived table in that it is not stored as an object and lasts only for the duration of the query. Unlike a derived table, a CTE can be self-referencing and can be referenced multiple times in the same query.
Where are CTE’s used?
A CTE can be used to:
Using a CTE offers the advantages of improved readability and ease in maintenance of complex queries. The query can be divided into separate, simple, logical building blocks. These simple blocks can then be used to build more complex, interim CTEs until the final result set is generated.
CTEs can be defined in user-defined routines, such as functions, stored procedures, triggers, or views
What is the structure of a CTE?
A CTE is made up of an expression name representing the CTE, an optional column list, and a query defining the CTE. After a CTE is defined, it can be referenced like a table or view can in a SELECT, INSERT, UPDATE, or DELETE statement. A CTE can also be used in a CREATE VIEW statement as part of its defining SELECT statement.
The basic syntax structure for a CTE is:
The list of column names is optional only if distinct names for all resulting columns are supplied in the query definition.
The statement to run the CTE is:
What are the restrictions of CTE’s?
A CTE is a local Transact-SQL statement and cannot be used in different places in the system
If the CTE is built from multiple tables and is used to query hierarchies those tables must be merged with UNION ALL;
CTE’s have the scope of a single SELECT, INSERT, DELETE or CREATE VIEW statement;
What is syntax of a common table expression?
[WITH [ ,…n] ]
::=
expression_name [( column_name [ ,…n] ) ]
AS
( CTE_query_definition )
What does the DECLARE CURSOR statement does?
Defines the attributes of a Transact-SQL server cursor, such as its scrolling behavior and the query used to build the result set on which the cursor operates. DECLARE CURSOR accepts both a syntax based on the ISO standard and a syntax using a set of Transact-SQL extensions.
What are some of the limitations of the declare cursor statement?
You cannot use cursors or triggers on a table with a clustered columnstore index. This restriction does not apply to nonclustered columnstore indexes; you can use cursors and triggers on a table with a nonclustered columnstore index.
What are some of the Guidelines for Creating and Using non recursive CTE’s?
What are some of the Guidelines for creating recursive’s CTE’s?
What are the guidelines to using a recursive common table expression?
All columns returned by the recursive CTE are nullable regardless of the nullability of the columns returned by the participating SELECT statements.
An incorrectly composed recursive CTE may cause an infinite loop. For example, if the recursive member query definition returns the same values for both the parent and child columns, an infinite loop is created. To prevent an infinite loop, you can limit the number of recursion levels allowed for a particular statement by using the MAXRECURSION hint and a value between 0 and 32,767 in the OPTION clause of the INSERT, UPDATE, DELETE, or SELECT statement. This lets you control the execution of the statement until you resolve the code problem that is creating the loop. The server-wide default is 100. When 0 is specified, no limit is applied. Only one MAXRECURSION value can be specified per statement. For more information, see Query Hints (Transact-SQL).
A view that contains a recursive common table expression cannot be used to update data.
Cursors may be defined on queries using CTEs. The CTE is the select_statement argument that defines the result set of the cursor. Only fast forward-only and static (snapshot) cursors are allowed for recursive CTEs. If another cursor type is specified in a recursive CTE, the cursor type is converted to static.
Tables on remote servers may be referenced in the CTE. If the remote server is referenced in the recursive member of the CTE, a spool is created for each remote table so the tables can be repeatedly accessed locally. If it is a CTE query, Index Spool/Lazy Spools is displayed in the query plan and will have the additional WITH STACK predicate. This is one way to confirm proper recursion.
Analytic and aggregate functions in the recursive part of the CTE are applied to the set for the current recursion level and not to the set for the CTE. Functions like ROW_NUMBER operate only on the subset of data passed to them by the current recursion level and not the entire set of data passed to the recursive part of the CTE. For more information, see example K. Using analytical functions in a recursive CTE that follows.
How may types of table expressions are there?
There are four types of table expressions:
DECLARE @local_variable (Transact-SQL) def
def: Variables are declared in the body of a batch or procedure with the DECLARE statement and are assigned values by using either a SET or SELECT statement. Cursor variables can be declared with this statement and used with other cursor-related statements. After declaration, all variables are initialized as NULL, unless a value is provided as part of the declaration.
DECLARE @local_variable (Transact-SQL) syntax
DECLARE
{
{ @local_variable [AS] data_type [= value] }
| { @cursor_variable_name CURSOR }
} [,…n]
::=
TABLE ( { | } [,…n] )
::=
column_name { scalar_data_type | AS computed_column_expression }
[COLLATE collation_name]
[[ DEFAULT constant_expression] | IDENTITY [(seed ,increment )] ]
[ROWGUIDCOL]
[]
::=
{ [NULL | NOT NULL]
| [PRIMARY KEY | UNIQUE]
| CHECK ( logical_expression )
| WITH ( ) }
::=
{ { PRIMARY KEY | UNIQUE } ( column_name [,…n] )
| CHECK ( search_condition ) }
::=
See CREATE TABLE for index option syntax.
{ @table_variable_name [AS] }
DECLARE @local_variable remarks
Variables are often used in a batch or procedure as counters for WHILE, LOOP, or for an IF…ELSE block.
Variables can be used only in expressions, not in place of object names or keywords. To construct dynamic SQL statements, use EXECUTE.
The scope of a local variable is the batch in which it is declared.
A table variable is not necessarily memory resident. Under memory pressure, the pages belonging to a table variable can be pushed out to tempdb.
A cursor variable that currently has a cursor assigned to it can be referenced as a source in a:
Positioned DELETE or UPDATE statement.
SET CURSOR variable statement (on the right side).
In all of these statements, SQL Server raises an error if a referenced cursor variable exists but does not have a cursor currently allocated to it. If a referenced cursor variable does not exist, SQL Server raises the same error raised for an undeclared variable of another type.
A cursor variable:
What is a batch of SQL statements?
A batch of SQL statements is a group of two or more SQL statements or a single SQL statement that has the same effect as a group of two or more SQL statements. In some implementations, the entire batch statement is executed before any results are available. This is often more efficient than submitting statements separately, because network traffic can often be reduced and the data source can sometimes optimize execution of a batch of SQL statements.
Types of batches:
what are the rules for using temporary tables?
You create a temp table, populate it, and reference it in future queries. This can lead to improved estimates and reliability, because temporary tables can have column and index related statistics. Those statistics help the optimizer estimate how many rows will be returned at different points along the way.
Temp tables are a great tool to use, but remember a few key rules: