SlideShare uma empresa Scribd logo
1 de 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

Mais conteúdo relacionado

Mais procurados (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
 

Destaque

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 2012ITCamp
 
Introduction to database & sql
Introduction to database & sqlIntroduction to database & sql
Introduction to database & sqlzahid6
 
Mastering T-SQL Window Functions
Mastering T-SQL Window FunctionsMastering T-SQL Window Functions
Mastering T-SQL Window FunctionsJose Rivera Miranda
 
Window functions with SQL Server 2016
Window functions with SQL Server 2016Window functions with SQL Server 2016
Window functions with SQL Server 2016Mark 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 UserImam 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 XEAchmad Solichin
 
Intro oracle10gexpress
Intro oracle10gexpressIntro oracle10gexpress
Intro oracle10gexpressjatin 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 JoinAjay Gupte
 
Oracle intro to designer abridged
Oracle intro to designer abridgedOracle intro to designer abridged
Oracle intro to designer abridgedFITSFSd
 
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 QueriesChema Alonso
 
T-SQL: Pivot, Unpivot, Except, Intersect
T-SQL: Pivot, Unpivot, Except, IntersectT-SQL: Pivot, Unpivot, Except, Intersect
T-SQL: Pivot, Unpivot, Except, IntersectBill 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 FunctionsZohar 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 Controlscottb411
 
Oracle dba trainining in hyderabad
Oracle dba trainining in hyderabadOracle dba trainining in hyderabad
Oracle dba trainining in hyderabadsreehari orienit
 

Destaque (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
 

Semelhante a T-SQL CTE Syntax Guide

Aggregate functions in SQL.pptx
Aggregate functions in SQL.pptxAggregate functions in SQL.pptx
Aggregate functions in SQL.pptxSherinRappai1
 
Assignment 3
Assignment 3Assignment 3
Assignment 3SneaK3
 
Aggregate functions in SQL.pptx
Aggregate functions in SQL.pptxAggregate functions in SQL.pptx
Aggregate functions in SQL.pptxSherinRappai
 
retrieving data using SQL statements
retrieving data using SQL statementsretrieving data using SQL statements
retrieving data using SQL statementsArun Nair
 
SignalR & SQL Dependency
SignalR & SQL DependencySignalR & SQL Dependency
SignalR & SQL DependencyNarato
 
Ms sql server ii
Ms sql server  iiMs sql server  ii
Ms sql server iiIblesoft
 
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, SubQueryAbhishek590097
 
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-dbuncleRhyme
 
Sql coding-standard-sqlserver
Sql coding-standard-sqlserverSql coding-standard-sqlserver
Sql coding-standard-sqlserverlochaaaa
 
Advanced Sql Training
Advanced Sql TrainingAdvanced Sql Training
Advanced Sql Trainingbixxman
 
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 knowPavithSingh
 
Sql select statement
Sql select statementSql select statement
Sql select statementVivek Singh
 

Semelhante a T-SQL CTE Syntax Guide (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
 

Mais de LearningTech

Mais 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
 

Último

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
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?Igalia
 
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...apidays
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 

Último (20)

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
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?
 
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...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 

T-SQL CTE Syntax Guide

  • 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