MOCKSTACKS
EN
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
 SELECT 1
 --Top-level UNION ALL operator required for recursion
 UNION ALL
 --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;

i
1
2
3
4
5

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

Conclusion

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: mockstacks@gmail.com.


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 Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.