Search code examples
sqlsql-servermultiple-records

Adding Multiple Records to a table


I have a customer database I would like to add a set of Card numbers to. In the table there are multiple columns that will be the same, however the Card number will increase by 1 until finished. So for example... I want to add Gift cards 1 - 250 with the other columns the same... so it would like something like this:

Cardnum      price    booktype   service 
1             9.99       1         12 
2             9.99       1         12
3             9.99       1         12

etc etc... This would repeat until cardnum was '250' Is it possible to do this with an SQL Query?

Thanks.


Solution

  • @jimdrang already provided the answer, but since I was just finishing a full example with the CREATE TABLE and a stored procedure to do the job, I guess I might as well post it for the benefit of anyone looking for this down the road.

    CREATE TABLE Cards
    (
      Cardnum int not null primary key,
      price money not null,
      booktype int not null,
      service int not null
    );
    GO
    
    CREATE PROCEDURE [dbo].[sp_AddCards] (
      @Price money,
      @BookType int,
      @Service int,
      @NumCards int,
      @StartNum int
    )
      AS
    BEGIN
      DECLARE @CurCard int
      SELECT @CurCard = @StartNum
    
      WHILE @CurCard < @StartNum + @NumCards
      BEGIN
        INSERT INTO Cards (Cardnum, price, booktype, service)
        VALUES (@CurCard, @Price, @BookType, @Service)
    
        SELECT @CurCard = @CurCard + 1
      END
    END
    
    GO
    
    EXEC sp_AddCards @Price=9.99, @BookType=1, @Service=12, @NumCards=250, @Startnum=810041;
    
    SELECT * FROM Cards;
    
    DROP TABLE Cards;
    DROP PROCEDURE sp_AddCards;
    

    Hope it helps!