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

后端 未结 3 1637
无人及你
无人及你 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

    Besides the detailed answer I pointed to in my comment, this is the idea in short:

    DECLARE @start INT=0;
    DECLARE @end INT=19; --0 to 19 are 20 days
    
    DECLARE @StartDate DATE={d'2016-01-01'};
    
    --Create a List of up to 1.000.000.000 rows on the fly
    --This is limited by start and end parameter
    
    ;WITH x AS(SELECT 1 AS N FROM(VALUES(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) AS tbl(N))--10^1
    ,N3 AS (SELECT 1 AS N FROM x CROSS JOIN x AS N2 CROSS JOIN x N3) --10^3
    ,Tally AS(SELECT TOP(@end-@start +1) ROW_NUMBER() OVER(ORDER BY(SELECT NULL)) + @start -1 AS Nr FROM N3 
              CROSS JOIN N3 N6 CROSS JOIN N3 AS N9)
    
    --INSERT INTO your_table
    
    SELECT @val2 --your @val2 here as a constant value
          ,DATEADD(DAY,Nr,@StartDate)
    FROM Tally
    

提交回复
热议问题