转载:SQL Server vs. Oracle: Generate Series or List of Numbers
To generate a list of numbers or series in Oracle or SQL Server, we need to use recursive CTE, if we call the CTE within the CTE then it is called recursive CTE.
# SQL Server
1 | WITH REC_CTE(ROW_NUM) AS ( |
# Oracle
# Oracle 11g version 2 and higher
1 | WITH REC_CTE(ROW_NUM) AS ( |
# Oracle Other
Oracle provides a set of hierarchy functions such as START WITH, LEVEL, PRIOR, CONNECT BY, CONNECT_BY_ROOT.
Example1:
1 | --below script will retrieve first hundred numbers |
Example2:
1 | --we can use level if we want to create a series from number other than 1 |
If you need to check the version of oracle, use below script.
1 | SELECT * FROM V$VERSION |
Above we have added 1 when we called the CTE with in CTE, if we add 2 then we will get even number series and so on.
# Comments
In SQL Server column alias list is not necessary, we can prune REC_CTE(ROW_NUM)
to REC_CTE
. But in Oracle will occurs ORA-32039: recursive WITH clause must have column alias list error.
1 | WITH REC_CTE AS ( |