SlideShare une entreprise Scribd logo
1  sur  22
T-SQL 語法之 CTE
2014/01/24
Bryan lin
Agenda
• Introduction
• Guidelines for creating and using CTE
• Guidelines for defining and using recursive CTE
• Examples
Introduction
• Suppose we have these SQL statement below:
Introduction
Introduction
• For these situation, we can use CTE(common_table_expression) to simplify our SQL
statement.
Introduction
• Syntax
Introduction
• Arguments
• expression_name
• Is a valid identifier for the common table expression. expression_name must be different from the
name of any other common table expression defined in the same WITH
<common_table_expression> clause, but expression_name can be the same as the name of a base
table or view. Any reference to expression_name in the query uses the common table expression
and not the base object.
Introduction
• Arguments
• column_name
• Specifies a column name in the common table expression. Duplicate names within a single CTE
definition are not allowed. The number of column names specified must match the number of
columns in the result set of the CTE_query_definition. The list of column names is optional only if
distinct names for all resulting columns are supplied in the query definition.
Introduction
• Arguments
• CTE_query_definition
• Specifies a SELECT statement whose result set populates the common table expression. The
SELECT statement for CTE_query_definition must meet the same requirements as for creating a
view, except a CTE cannot define another CTE. For more information, see the Remarks section and
CREATE VIEW (Transact-SQL).
Guidelines for creating and using CTE
• A CTE must be followed by a single SELECT, INSERT, UPDATE, or DELETE statement that references
some or all the CTE columns. A CTE can also be specified in a CREATE VIEW statement as part of the
defining SELECT statement of the view.
• Multiple CTE query definitions can be defined in a nonrecursive CTE. The definitions must be combined
by one of these set operators: UNION ALL, UNION, INTERSECT, or EXCEPT.
• A CTE can reference itself and previously defined CTEs in the same WITH clause. Forward referencing
is not allowed.
• Specifying more than one WITH clause in a CTE is not allowed. For example, if a CTE_query_definition
contains a subquery, that subquery cannot contain a nested WITH clause that defines another CTE.
Guidelines for creating and using CTE
• The following clauses cannot be used in the CTE_query_definition:
• ORDER BY (except when a TOP clause is specified)
• INTO
• OPTION clause with query hints
• FOR BROWSE

• When a CTE is used in a statement that is part of a batch, the statement before it must
be followed by a semicolon.

• A query referencing a CTE can be used to define a cursor.
Guidelines for creating and using CTE
• Tables on remote servers can be referenced in the CTE.
• When executing a CTE, any hints that reference a CTE may conflict with other hints that
are discovered when the CTE accesses its underlying tables, in the same manner as
hints that reference views in queries. When this occurs, the query returns an error.
Guidelines for Defining and Using Recursive
Common Table Expressions
• The recursive CTE definition must contain at least two CTE query definitions, an anchor
member and a recursive member. Multiple anchor members and recursive members can be
defined; however, all anchor member query definitions must be put before the first recursive
member definition. All CTE query definitionsare anchor members unless they reference the
CTE itself.
• Anchor members must be combined by one of these set operators: UNION
ALL, UNION, INTERSECT, or EXCEPT. UNION ALL is the only set operator allowed between
the last anchor member and first recursive member, and when combining multiple recursive
members.
• The number of columns in the anchor and recursive members must be the same.
Guidelines for Defining and Using Recursive
Common Table Expressions
• The data type of a column in the recursive member must be the same as the data type of the
corresponding column in the anchor member.
• The FROM clause of a recursive member must refer only one time to the CTE expression_name.
• The following items are not allowed in the CTE_query_definition of a recursive member:
• SELECT DISTINCT
• GROUP BY
• PIVOT (When the database compatibility level is 110. See Breaking Changes to Database Engine Features in
SQL Server 2012.)
• HAVING
• Scalar aggregation
Guidelines for Defining and Using Recursive
Common Table Expressions
• TOP
• LEFT, RIGHT, OUTER JOIN (INNER JOIN is allowed)
• Subqueries
• A hint applied to a recursive reference to a CTE inside a CTE_query_definition.
Guidelines for Defining and Using Recursive
Common Table Expressions
• 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.
Guidelines for Defining and Using Recursive
Common Table Expressions
• 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 pased to the recursive part of
the CTE. For more information, see J. Using analytical functions in a recursive CTE.
Examples
• Creating a simple common table expression
Examples
• Using multiple CTE definitions in a single query
Examples
• Using a recursive common table expression to display multiple levels of recursion
FAQ
References
• http://msdn.microsoft.com/en-us/library/ms175972.aspx

Contenu connexe

Tendances

On if,countif,countifs,sumif,countifs,lookup,v lookup,index,match
On if,countif,countifs,sumif,countifs,lookup,v lookup,index,matchOn if,countif,countifs,sumif,countifs,lookup,v lookup,index,match
On if,countif,countifs,sumif,countifs,lookup,v lookup,index,match
Rakesh Sah
 
Web topic 12 tables in html
Web topic 12  tables in htmlWeb topic 12  tables in html
Web topic 12 tables in html
CK Yang
 

Tendances (20)

Advance database system(part 5)
Advance database system(part 5)Advance database system(part 5)
Advance database system(part 5)
 
On if,countif,countifs,sumif,countifs,lookup,v lookup,index,match
On if,countif,countifs,sumif,countifs,lookup,v lookup,index,matchOn if,countif,countifs,sumif,countifs,lookup,v lookup,index,match
On if,countif,countifs,sumif,countifs,lookup,v lookup,index,match
 
advanced sql(database)
advanced sql(database)advanced sql(database)
advanced sql(database)
 
Bt0075 rdbms with mysql 2
Bt0075 rdbms with mysql 2Bt0075 rdbms with mysql 2
Bt0075 rdbms with mysql 2
 
Excel SUMIFS Function
Excel SUMIFS FunctionExcel SUMIFS Function
Excel SUMIFS Function
 
Tabulation of data
Tabulation of dataTabulation of data
Tabulation of data
 
Types of table
Types of tableTypes of table
Types of table
 
Joins and unions
Joins and unionsJoins and unions
Joins and unions
 
MS excel functions
MS excel functionsMS excel functions
MS excel functions
 
Advance excel
Advance excelAdvance excel
Advance excel
 
Introduction to the Relational Model and SQL
Introduction to the Relational Model and SQLIntroduction to the Relational Model and SQL
Introduction to the Relational Model and SQL
 
Dbms.....SQL statemets
Dbms.....SQL statemetsDbms.....SQL statemets
Dbms.....SQL statemets
 
Tabulation
TabulationTabulation
Tabulation
 
Unit 5 composite datatypes
Unit 5  composite datatypesUnit 5  composite datatypes
Unit 5 composite datatypes
 
Roshdy salem
Roshdy salemRoshdy salem
Roshdy salem
 
Microsoft Excel VLOOKUP Function
Microsoft Excel VLOOKUP FunctionMicrosoft Excel VLOOKUP Function
Microsoft Excel VLOOKUP Function
 
How oracle query works (The SQL Optimizers)
How oracle query works (The SQL Optimizers)How oracle query works (The SQL Optimizers)
How oracle query works (The SQL Optimizers)
 
Ses 4 tabulation
Ses 4 tabulationSes 4 tabulation
Ses 4 tabulation
 
Optimizer hint
Optimizer hintOptimizer hint
Optimizer hint
 
Web topic 12 tables in html
Web topic 12  tables in htmlWeb topic 12  tables in html
Web topic 12 tables in html
 

En vedette

ITCamp 2013 - Cristian Lefter - Transact-SQL from 0 to SQL Server 2012
ITCamp 2013 - Cristian Lefter - Transact-SQL from 0 to SQL Server 2012ITCamp 2013 - Cristian Lefter - Transact-SQL from 0 to SQL Server 2012
ITCamp 2013 - Cristian Lefter - Transact-SQL from 0 to SQL Server 2012
ITCamp
 
Intro oracle10gexpress
Intro oracle10gexpressIntro oracle10gexpress
Intro oracle10gexpress
jatin Sareen
 
Oracle intro to designer abridged
Oracle intro to designer abridgedOracle intro to designer abridged
Oracle intro to designer abridged
FITSFSd
 

En vedette (20)

ITCamp 2013 - Cristian Lefter - Transact-SQL from 0 to SQL Server 2012
ITCamp 2013 - Cristian Lefter - Transact-SQL from 0 to SQL Server 2012ITCamp 2013 - Cristian Lefter - Transact-SQL from 0 to SQL Server 2012
ITCamp 2013 - Cristian Lefter - Transact-SQL from 0 to SQL Server 2012
 
Introduction to database & sql
Introduction to database & sqlIntroduction to database & sql
Introduction to database & sql
 
Mastering T-SQL Window Functions
Mastering T-SQL Window FunctionsMastering T-SQL Window Functions
Mastering T-SQL Window Functions
 
Data twisting
Data twistingData twisting
Data twisting
 
Window functions with SQL Server 2016
Window functions with SQL Server 2016Window functions with SQL Server 2016
Window functions with SQL Server 2016
 
Sql server ___________session 2(sql 2008)
Sql server  ___________session 2(sql 2008)Sql server  ___________session 2(sql 2008)
Sql server ___________session 2(sql 2008)
 
Tutorial Instalisasi Oracle 10g dan Setting User
Tutorial Instalisasi Oracle 10g dan Setting UserTutorial Instalisasi Oracle 10g dan Setting User
Tutorial Instalisasi Oracle 10g dan Setting User
 
Intro to Application Express
Intro to Application ExpressIntro to Application Express
Intro to Application Express
 
Step By Step How To Install Oracle XE
Step By Step How To Install Oracle XEStep By Step How To Install Oracle XE
Step By Step How To Install Oracle XE
 
Intro oracle10gexpress
Intro oracle10gexpressIntro oracle10gexpress
Intro oracle10gexpress
 
IBM Informix Database SQL Set operators and ANSI Hash Join
IBM Informix Database SQL Set operators and ANSI Hash JoinIBM Informix Database SQL Set operators and ANSI Hash Join
IBM Informix Database SQL Set operators and ANSI Hash Join
 
Oracle intro to designer abridged
Oracle intro to designer abridgedOracle intro to designer abridged
Oracle intro to designer abridged
 
Sql server ___________ (advance sql)
Sql server  ___________  (advance sql)Sql server  ___________  (advance sql)
Sql server ___________ (advance sql)
 
Time-Based Blind SQL Injection using Heavy Queries
Time-Based Blind SQL Injection using Heavy QueriesTime-Based Blind SQL Injection using Heavy Queries
Time-Based Blind SQL Injection using Heavy Queries
 
T-SQL: Pivot, Unpivot, Except, Intersect
T-SQL: Pivot, Unpivot, Except, IntersectT-SQL: Pivot, Unpivot, Except, Intersect
T-SQL: Pivot, Unpivot, Except, Intersect
 
Oracle database introduction
Oracle database introductionOracle database introduction
Oracle database introduction
 
Exploring Advanced SQL Techniques Using Analytic Functions
Exploring Advanced SQL Techniques Using Analytic FunctionsExploring Advanced SQL Techniques Using Analytic Functions
Exploring Advanced SQL Techniques Using Analytic Functions
 
Managing Oracle Streams Using Enterprise Manager Grid Control
Managing Oracle Streams Using Enterprise Manager Grid ControlManaging Oracle Streams Using Enterprise Manager Grid Control
Managing Oracle Streams Using Enterprise Manager Grid Control
 
Transaction
TransactionTransaction
Transaction
 
Oracle dba trainining in hyderabad
Oracle dba trainining in hyderabadOracle dba trainining in hyderabad
Oracle dba trainining in hyderabad
 

Similaire à T sql語法之 cte 20140214

retrieving data using SQL statements
retrieving data using SQL statementsretrieving data using SQL statements
retrieving data using SQL statements
Arun Nair
 
Ms sql server ii
Ms sql server  iiMs sql server  ii
Ms sql server ii
Iblesoft
 
02 database oprimization - improving sql performance - ent-db
02  database oprimization - improving sql performance - ent-db02  database oprimization - improving sql performance - ent-db
02 database oprimization - improving sql performance - ent-db
uncleRhyme
 
Sql coding-standard-sqlserver
Sql coding-standard-sqlserverSql coding-standard-sqlserver
Sql coding-standard-sqlserver
lochaaaa
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good know
PavithSingh
 
Sql select statement
Sql select statementSql select statement
Sql select statement
Vivek Singh
 

Similaire à T sql語法之 cte 20140214 (20)

Aggregate functions in SQL.pptx
Aggregate functions in SQL.pptxAggregate functions in SQL.pptx
Aggregate functions in SQL.pptx
 
Assignment 3
Assignment 3Assignment 3
Assignment 3
 
Aggregate functions in SQL.pptx
Aggregate functions in SQL.pptxAggregate functions in SQL.pptx
Aggregate functions in SQL.pptx
 
retrieving data using SQL statements
retrieving data using SQL statementsretrieving data using SQL statements
retrieving data using SQL statements
 
ADVANCED MODELLING.pptx
ADVANCED MODELLING.pptxADVANCED MODELLING.pptx
ADVANCED MODELLING.pptx
 
Merging data (1)
Merging data (1)Merging data (1)
Merging data (1)
 
SignalR & SQL Dependency
SignalR & SQL DependencySignalR & SQL Dependency
SignalR & SQL Dependency
 
Ms sql server ii
Ms sql server  iiMs sql server  ii
Ms sql server ii
 
Sql2
Sql2Sql2
Sql2
 
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
PPT  of Common Table Expression (CTE), Window Functions, JOINS, SubQueryPPT  of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
 
2..basic queries.pptx
2..basic queries.pptx2..basic queries.pptx
2..basic queries.pptx
 
MULTIPLE TABLES
MULTIPLE TABLES MULTIPLE TABLES
MULTIPLE TABLES
 
02 database oprimization - improving sql performance - ent-db
02  database oprimization - improving sql performance - ent-db02  database oprimization - improving sql performance - ent-db
02 database oprimization - improving sql performance - ent-db
 
Interview Questions.pdf
Interview Questions.pdfInterview Questions.pdf
Interview Questions.pdf
 
Sql coding-standard-sqlserver
Sql coding-standard-sqlserverSql coding-standard-sqlserver
Sql coding-standard-sqlserver
 
Advanced Sql Training
Advanced Sql TrainingAdvanced Sql Training
Advanced Sql Training
 
SQL Commands
SQL Commands SQL Commands
SQL Commands
 
MS SQL Server
MS SQL ServerMS SQL Server
MS SQL Server
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good know
 
Sql select statement
Sql select statementSql select statement
Sql select statement
 

Plus de LearningTech (20)

vim
vimvim
vim
 
PostCss
PostCssPostCss
PostCss
 
ReactJs
ReactJsReactJs
ReactJs
 
Docker
DockerDocker
Docker
 
Semantic ui
Semantic uiSemantic ui
Semantic ui
 
node.js errors
node.js errorsnode.js errors
node.js errors
 
Process control nodejs
Process control nodejsProcess control nodejs
Process control nodejs
 
Expression tree
Expression treeExpression tree
Expression tree
 
SQL 效能調校
SQL 效能調校SQL 效能調校
SQL 效能調校
 
flexbox report
flexbox reportflexbox report
flexbox report
 
Vic weekly learning_20160504
Vic weekly learning_20160504Vic weekly learning_20160504
Vic weekly learning_20160504
 
Reflection &amp; activator
Reflection &amp; activatorReflection &amp; activator
Reflection &amp; activator
 
Peggy markdown
Peggy markdownPeggy markdown
Peggy markdown
 
Node child process
Node child processNode child process
Node child process
 
20160415ken.lee
20160415ken.lee20160415ken.lee
20160415ken.lee
 
Peggy elasticsearch應用
Peggy elasticsearch應用Peggy elasticsearch應用
Peggy elasticsearch應用
 
Expression tree
Expression treeExpression tree
Expression tree
 
Vic weekly learning_20160325
Vic weekly learning_20160325Vic weekly learning_20160325
Vic weekly learning_20160325
 
D3js learning tips
D3js learning tipsD3js learning tips
D3js learning tips
 
git command
git commandgit command
git command
 

Dernier

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Dernier (20)

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 

T sql語法之 cte 20140214

  • 2. Agenda • Introduction • Guidelines for creating and using CTE • Guidelines for defining and using recursive CTE • Examples
  • 3. Introduction • Suppose we have these SQL statement below:
  • 5. Introduction • For these situation, we can use CTE(common_table_expression) to simplify our SQL statement.
  • 7. Introduction • Arguments • expression_name • Is a valid identifier for the common table expression. expression_name must be different from the name of any other common table expression defined in the same WITH <common_table_expression> clause, but expression_name can be the same as the name of a base table or view. Any reference to expression_name in the query uses the common table expression and not the base object.
  • 8. Introduction • Arguments • column_name • Specifies a column name in the common table expression. Duplicate names within a single CTE definition are not allowed. The number of column names specified must match the number of columns in the result set of the CTE_query_definition. The list of column names is optional only if distinct names for all resulting columns are supplied in the query definition.
  • 9. Introduction • Arguments • CTE_query_definition • Specifies a SELECT statement whose result set populates the common table expression. The SELECT statement for CTE_query_definition must meet the same requirements as for creating a view, except a CTE cannot define another CTE. For more information, see the Remarks section and CREATE VIEW (Transact-SQL).
  • 10. Guidelines for creating and using CTE • A CTE must be followed by a single SELECT, INSERT, UPDATE, or DELETE statement that references some or all the CTE columns. A CTE can also be specified in a CREATE VIEW statement as part of the defining SELECT statement of the view. • Multiple CTE query definitions can be defined in a nonrecursive CTE. The definitions must be combined by one of these set operators: UNION ALL, UNION, INTERSECT, or EXCEPT. • A CTE can reference itself and previously defined CTEs in the same WITH clause. Forward referencing is not allowed. • Specifying more than one WITH clause in a CTE is not allowed. For example, if a CTE_query_definition contains a subquery, that subquery cannot contain a nested WITH clause that defines another CTE.
  • 11. Guidelines for creating and using CTE • The following clauses cannot be used in the CTE_query_definition: • ORDER BY (except when a TOP clause is specified) • INTO • OPTION clause with query hints • FOR BROWSE • When a CTE is used in a statement that is part of a batch, the statement before it must be followed by a semicolon. • A query referencing a CTE can be used to define a cursor.
  • 12. Guidelines for creating and using CTE • Tables on remote servers can be referenced in the CTE. • When executing a CTE, any hints that reference a CTE may conflict with other hints that are discovered when the CTE accesses its underlying tables, in the same manner as hints that reference views in queries. When this occurs, the query returns an error.
  • 13. Guidelines for Defining and Using Recursive Common Table Expressions • The recursive CTE definition must contain at least two CTE query definitions, an anchor member and a recursive member. Multiple anchor members and recursive members can be defined; however, all anchor member query definitions must be put before the first recursive member definition. All CTE query definitionsare anchor members unless they reference the CTE itself. • Anchor members must be combined by one of these set operators: UNION ALL, UNION, INTERSECT, or EXCEPT. UNION ALL is the only set operator allowed between the last anchor member and first recursive member, and when combining multiple recursive members. • The number of columns in the anchor and recursive members must be the same.
  • 14. Guidelines for Defining and Using Recursive Common Table Expressions • The data type of a column in the recursive member must be the same as the data type of the corresponding column in the anchor member. • The FROM clause of a recursive member must refer only one time to the CTE expression_name. • The following items are not allowed in the CTE_query_definition of a recursive member: • SELECT DISTINCT • GROUP BY • PIVOT (When the database compatibility level is 110. See Breaking Changes to Database Engine Features in SQL Server 2012.) • HAVING • Scalar aggregation
  • 15. Guidelines for Defining and Using Recursive Common Table Expressions • TOP • LEFT, RIGHT, OUTER JOIN (INNER JOIN is allowed) • Subqueries • A hint applied to a recursive reference to a CTE inside a CTE_query_definition.
  • 16. Guidelines for Defining and Using Recursive Common Table Expressions • 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.
  • 17. Guidelines for Defining and Using Recursive Common Table Expressions • 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 pased to the recursive part of the CTE. For more information, see J. Using analytical functions in a recursive CTE.
  • 18. Examples • Creating a simple common table expression
  • 19. Examples • Using multiple CTE definitions in a single query
  • 20. Examples • Using a recursive common table expression to display multiple levels of recursion
  • 21. FAQ