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

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

提交回复
热议问题