Questions And Answers

More Tutorials

SQLServer Common Table Expressions

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 Numbers with a column i which has a row for numbers 1-5:

--Give a table name `Numbers" and a column `i` to hold the numbers
WITH Numbers(i) AS (
 --Starting number/index
 --Top-level UNION ALL operator required for recursion
 --Iteration expression:
 SELECT i + 1
 --Table expression we first declared used as source for recursion
 FROM Numbers
 --Clause to define the end of the recursion
 WHERE i < 5
--Use the generated table expression like a regular table
SELECT i FROM Numbers;


This method can be used with any number interval, as well as other types of data.


In this page (written and validated by ) you learned about SQLServer Common Table Expressions . What's Next? If you are interested in completing SQLServer tutorial, your next topic will be learning about: SQLServer Views.

Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue:

Share On:

Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using, you agree to have read and accepted our terms of use, cookies and privacy policy.