| Start | ||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| generating values Most databases do not have a native way of generating a series of numbers for ad-hoc use; however, common table expressions can be used with recursion to emulate that type of function. The following example generates a common table expression called
This method can be used with any number interval, as well as other types of data. |
||||||||||||||||||||||||
recursively enumerating a subtree
|
||||||||||||||||||||||||
| Temporary query These behave in the same manner as nested subqueries but with a different syntax.
Equivalent subquery syntax |
||||||||||||||||||||||||
recursively going up in a tree
|
||||||||||||||||||||||||
Recursively generate dates, extended to include team rostering as example Result I.e. For Week 1 TeamA is on R&R, TeamB is on Day Shift and TeamC is on Night Shift. |
||||||||||||||||||||||||
| Oracle CONNECT BY functionality with recursive CTEs Oracle's CONNECT BY functionality provides many useful and nontrivial features that are not built-in when using SQL standard recursive CTEs. This example replicates these features (with a few additions for sake of completeness), using SQL Server syntax. It is most useful for Oracle developers finding many features missing in their hierarchical queries on other databases, but it also serves to showcase what can be done with a hierarchical query in general. CONNECT BY features demonstrated above, with explanations:
|
||||||||||||||||||||||||
| Refactoring a query to use Common Table Expressions Suppose we want to get all product categories with total sales greater than 20. Here is a query without Common Table Expressions: And an equivalent query using Common Table Expressions: |
||||||||||||||||||||||||
| Example of a complex SQL with Common Table Expression Suppose we want to query the "cheapest products" from the "top categories". Here is an example of query using Common Table Expressions SyntaxWITH QueryName [(ColumnName, ...)] AS ( WITH RECURSIVE QueryName [(ColumnName, ...)] AS ( RemarksOfficial documentation: WITH clause (opens new window) A Common Table Expression is a temporary result set, and it can be result of complex sub query. It is defined by using WITH clause. CTE improves readability and it is created in memory rather than TempDB database where Temp Table and Table variable is created. Key concepts of Common Table Expressions:
|
Read Article
https://develop.horje.com/learn/1434/reference