How to insert multiple rows into a table based on a range of numbers

后端 未结 3 1663
无人及你
无人及你 2021-01-27 07:19

I have to insert a specific number of rows into a SQL Server table.

DECLARE @val AS INT = 20, 
        @val2 AS VARCHAR(50), 
        @Date AS DATETIME = CONVER         


        
3条回答
  •  遇见更好的自我
    2021-01-27 07:47

    You could use a recursive CTE.

    DECLARE @i INT = 1
        , @m INT = 19
        , @d DATETIME2 = '2016-05-02';
    
    WITH i AS (
        SELECT 0 AS increment
        UNION ALL
        SELECT i.increment + @i
        FROM i
        WHERE i.increment < @m
    )
    SELECT i.increment
        , DATEADD(DAY, i.increment, @d)
    FROM i
    OPTION (MAXRECURSION 100);
    

    Note the OPTION (MAXRECUSION 100) hint at the bottom, which is not strictly necessary but I have included it to illustrate how it works. By default, there is a limit of 100 results using this method, so without this statement and if @m were a large number e.g. 1000 then SQL would generate an error. You can set the lmit to 0 which means unbounded, but only do this after testing your code, because it can get stuck in an infinite loop this way (which is why the limit exists by default).

提交回复
热议问题