Is there a generic way to generate an arbitrary linear sequence in SQL?

前端 未结 6 934
被撕碎了的回忆
被撕碎了的回忆 2021-01-13 02:37

Is there a SQL query I can do that will generate a linear sequence like

1, 2, 3, 4, 5, 6, 7 ... x+1

or

2, 7, 12, 17, 22 ...         


        
6条回答
  •  独厮守ぢ
    2021-01-13 03:07

    SQL Server and Oracle now implement the ANSI standard ROW_NUMBER() windowing function, but you'd need a table to work off of:

    SELECT ROW_NUMBER() OVER (ORDER BY ID) AS __ROW, ID, Name
    FROM SomethingWithANameAndAnID
    ORDER BY __ROW;
    

    Or you could use a recursive Common Table Expression in SQL Server (not sure if Oracle implements this yet):

    WITH cte AS
    (
        SELECT 1 AS num
        UNION ALL
        SELECT (num + 1) AS num FROM cte
        WHERE num < @SomeMaximum
    )
    SELECT * FROM cte OPTION (MAXRECURSION 0);
    

    Note that without the MAXRECURSION option CTE recursion depth in MS SQL is limited to 100. (value of 0 disables the recursion limit)

提交回复
热议问题