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

后端 未结 3 1600
无人及你
无人及你 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
    
    0 讨论(0)
  • 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).

    0 讨论(0)
  • 2021-01-27 07:51

    You can use a numbers table if you have one, use master.dbo.spt_values if you want one that has values till 2048, or create one of your own. In this case, you could use master.dbo.spt_values:

    DECLARE @val AS INT=20, @val2 AS VARCHAR(50);
    DECLARE @Date AS DATETIME = CONVERT(DATETIME,'02-05-2016');
    
    SET @val2 = 'abc'
    
    INSERT INTO dbo.YourTable
    SELECT @val2, DATEADD(DAY,number,@Date)
    FROM master.dbo.spt_values
    WHERE type = 'P'
    AND number <= @val;
    

    Though since this starts at zero, you'll get 21 rows as a result

    0 讨论(0)
提交回复
热议问题