SlideShare a Scribd company logo
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
Ad

More Related Content

What's hot (20)

Advance database system(part 5)
Advance database system(part 5)Advance database system(part 5)
Advance database system(part 5)
Abdullah Khosa
 
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
 
advanced sql(database)
advanced sql(database)advanced sql(database)
advanced sql(database)
welcometofacebook
 
Bt0075 rdbms with mysql 2
Bt0075 rdbms with mysql 2Bt0075 rdbms with mysql 2
Bt0075 rdbms with mysql 2
Techglyphs
 
Excel SUMIFS Function
Excel SUMIFS FunctionExcel SUMIFS Function
Excel SUMIFS Function
Excel
 
Tabulation of data
Tabulation of dataTabulation of data
Tabulation of data
RekhaChoudhary24
 
Types of table
Types of tableTypes of table
Types of table
Manoj Kumar
 
Joins and unions
Joins and unionsJoins and unions
Joins and unions
baabtra.com - No. 1 supplier of quality freshers
 
MS excel functions
MS excel functionsMS excel functions
MS excel functions
Marsha Superio
 
Advance excel
Advance excelAdvance excel
Advance excel
SiddheshHadge
 
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
LGS, GBHS&IC, University Of South-Asia, TARA-Technologies
 
Dbms.....SQL statemets
Dbms.....SQL statemetsDbms.....SQL statemets
Dbms.....SQL statemets
Rajeshwari Netha
 
Tabulation
TabulationTabulation
Tabulation
Nirmal Singh
 
Unit 5 composite datatypes
Unit 5  composite datatypesUnit 5  composite datatypes
Unit 5 composite datatypes
DrkhanchanaR
 
Roshdy salem
Roshdy salemRoshdy salem
Roshdy salem
Roushdy Salem
 
Microsoft Excel VLOOKUP Function
Microsoft Excel VLOOKUP FunctionMicrosoft Excel VLOOKUP Function
Microsoft Excel VLOOKUP Function
Excel
 
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)
Hosein Zare
 
Ses 4 tabulation
Ses 4 tabulationSes 4 tabulation
Ses 4 tabulation
metnashikiom2011-13
 
Optimizer hint
Optimizer hintOptimizer hint
Optimizer hint
Rajeev Rastogi (KRR)
 
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
 

Viewers also liked (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
ITCamp
 
Introduction to database & sql
Introduction to database & sqlIntroduction to database & sql
Introduction to database & sql
zahid6
 
Mastering T-SQL Window Functions
Mastering T-SQL Window FunctionsMastering T-SQL Window Functions
Mastering T-SQL Window Functions
Jose Rivera Miranda
 
Data twisting
Data twistingData twisting
Data twisting
Kim Berg Hansen
 
Window functions with SQL Server 2016
Window functions with SQL Server 2016Window functions with SQL Server 2016
Window functions with SQL Server 2016
Mark Tabladillo
 
Sql server ___________session 2(sql 2008)
Sql server  ___________session 2(sql 2008)Sql server  ___________session 2(sql 2008)
Sql server ___________session 2(sql 2008)
Ehtisham Ali
 
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
Imam Halim Mursyidin
 
Intro to Application Express
Intro to Application ExpressIntro to Application Express
Intro to Application Express
José Angel Ibarra Espinosa
 
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
Achmad Solichin
 
Intro oracle10gexpress
Intro oracle10gexpressIntro oracle10gexpress
Intro oracle10gexpress
jatin Sareen
 
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
Ajay Gupte
 
Oracle intro to designer abridged
Oracle intro to designer abridgedOracle intro to designer abridged
Oracle intro to designer abridged
FITSFSd
 
Sql server ___________ (advance sql)
Sql server  ___________  (advance sql)Sql server  ___________  (advance sql)
Sql server ___________ (advance sql)
Ehtisham Ali
 
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
Chema Alonso
 
T-SQL: Pivot, Unpivot, Except, Intersect
T-SQL: Pivot, Unpivot, Except, IntersectT-SQL: Pivot, Unpivot, Except, Intersect
T-SQL: Pivot, Unpivot, Except, Intersect
Bill Lin
 
Oracle database introduction
Oracle database introductionOracle database introduction
Oracle database introduction
Mohammad Javad Beheshtian
 
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
Zohar Elkayam
 
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
scottb411
 
Transaction
TransactionTransaction
Transaction
Dimara Hakim
 
Oracle dba trainining in hyderabad
Oracle dba trainining in hyderabadOracle dba trainining in hyderabad
Oracle dba trainining in hyderabad
sreehari orienit
 
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
 
Introduction to database & sql
Introduction to database & sqlIntroduction to database & sql
Introduction to database & sql
zahid6
 
Mastering T-SQL Window Functions
Mastering T-SQL Window FunctionsMastering T-SQL Window Functions
Mastering T-SQL Window Functions
Jose Rivera Miranda
 
Window functions with SQL Server 2016
Window functions with SQL Server 2016Window functions with SQL Server 2016
Window functions with SQL Server 2016
Mark Tabladillo
 
Sql server ___________session 2(sql 2008)
Sql server  ___________session 2(sql 2008)Sql server  ___________session 2(sql 2008)
Sql server ___________session 2(sql 2008)
Ehtisham Ali
 
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
Imam Halim Mursyidin
 
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
Achmad Solichin
 
Intro oracle10gexpress
Intro oracle10gexpressIntro oracle10gexpress
Intro oracle10gexpress
jatin Sareen
 
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
Ajay Gupte
 
Oracle intro to designer abridged
Oracle intro to designer abridgedOracle intro to designer abridged
Oracle intro to designer abridged
FITSFSd
 
Sql server ___________ (advance sql)
Sql server  ___________  (advance sql)Sql server  ___________  (advance sql)
Sql server ___________ (advance sql)
Ehtisham Ali
 
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
Chema Alonso
 
T-SQL: Pivot, Unpivot, Except, Intersect
T-SQL: Pivot, Unpivot, Except, IntersectT-SQL: Pivot, Unpivot, Except, Intersect
T-SQL: Pivot, Unpivot, Except, Intersect
Bill Lin
 
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
Zohar Elkayam
 
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
scottb411
 
Oracle dba trainining in hyderabad
Oracle dba trainining in hyderabadOracle dba trainining in hyderabad
Oracle dba trainining in hyderabad
sreehari orienit
 
Ad

Similar to T sql語法之 cte 20140214 (20)

Aggregate functions in SQL.pptx
Aggregate functions in SQL.pptxAggregate functions in SQL.pptx
Aggregate functions in SQL.pptx
SherinRappai1
 
Assignment 3
Assignment 3Assignment 3
Assignment 3
SneaK3
 
Aggregate functions in SQL.pptx
Aggregate functions in SQL.pptxAggregate functions in SQL.pptx
Aggregate functions in SQL.pptx
SherinRappai
 
More Complex SQL and Concurrency ControlModule 4.pptx
More Complex SQL and Concurrency ControlModule 4.pptxMore Complex SQL and Concurrency ControlModule 4.pptx
More Complex SQL and Concurrency ControlModule 4.pptx
bgscseise
 
retrieving data using SQL statements
retrieving data using SQL statementsretrieving data using SQL statements
retrieving data using SQL statements
Arun Nair
 
Structure query language, database course
Structure query language, database courseStructure query language, database course
Structure query language, database course
yunussufyan2024
 
ADVANCED MODELLING.pptx
ADVANCED MODELLING.pptxADVANCED MODELLING.pptx
ADVANCED MODELLING.pptx
RUPAK BHATTACHARJEE
 
Merging data (1)
Merging data (1)Merging data (1)
Merging data (1)
Ris Fernandez
 
SignalR & SQL Dependency
SignalR & SQL DependencySignalR & SQL Dependency
SignalR & SQL Dependency
Narato
 
Ms sql server ii
Ms sql server  iiMs sql server  ii
Ms sql server ii
Iblesoft
 
Sql2
Sql2Sql2
Sql2
LuisDeLeon74
 
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
Abhishek590097
 
Understanding Structured Query Language fundamentals
Understanding Structured Query Language fundamentalsUnderstanding Structured Query Language fundamentals
Understanding Structured Query Language fundamentals
Ankit Rao
 
2..basic queries.pptx
2..basic queries.pptx2..basic queries.pptx
2..basic queries.pptx
MalaikaRahatQurashi
 
MULTIPLE TABLES
MULTIPLE TABLES MULTIPLE TABLES
MULTIPLE TABLES
ASHABOOPATHY
 
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
 
Interview Questions.pdf
Interview Questions.pdfInterview Questions.pdf
Interview Questions.pdf
TarunKumar893717
 
Sql coding-standard-sqlserver
Sql coding-standard-sqlserverSql coding-standard-sqlserver
Sql coding-standard-sqlserver
lochaaaa
 
Advanced Sql Training
Advanced Sql TrainingAdvanced Sql Training
Advanced Sql Training
bixxman
 
SQL Commands
SQL Commands SQL Commands
SQL Commands
Sachidananda M H
 
Aggregate functions in SQL.pptx
Aggregate functions in SQL.pptxAggregate functions in SQL.pptx
Aggregate functions in SQL.pptx
SherinRappai1
 
Assignment 3
Assignment 3Assignment 3
Assignment 3
SneaK3
 
Aggregate functions in SQL.pptx
Aggregate functions in SQL.pptxAggregate functions in SQL.pptx
Aggregate functions in SQL.pptx
SherinRappai
 
More Complex SQL and Concurrency ControlModule 4.pptx
More Complex SQL and Concurrency ControlModule 4.pptxMore Complex SQL and Concurrency ControlModule 4.pptx
More Complex SQL and Concurrency ControlModule 4.pptx
bgscseise
 
retrieving data using SQL statements
retrieving data using SQL statementsretrieving data using SQL statements
retrieving data using SQL statements
Arun Nair
 
Structure query language, database course
Structure query language, database courseStructure query language, database course
Structure query language, database course
yunussufyan2024
 
SignalR & SQL Dependency
SignalR & SQL DependencySignalR & SQL Dependency
SignalR & SQL Dependency
Narato
 
Ms sql server ii
Ms sql server  iiMs sql server  ii
Ms sql server ii
Iblesoft
 
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
Abhishek590097
 
Understanding Structured Query Language fundamentals
Understanding Structured Query Language fundamentalsUnderstanding Structured Query Language fundamentals
Understanding Structured Query Language fundamentals
Ankit Rao
 
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
 
Advanced Sql Training
Advanced Sql TrainingAdvanced Sql Training
Advanced Sql Training
bixxman
 
Ad

More from LearningTech (20)

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

Recently uploaded (20)

Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 

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