Sql script to use a column from one table and populate another table

  • I have two tables Product table and Rate Table.

    Product

    ProductId Name

    Rate

    LevelId Cost ProductId

    Each Product has 7 Levels and cost for each level is 100, 200.... 700.

    I now need a script to take all the product Ids and Populate the Rate table , so that my end output would look like this :

    Rate

    LevelId Cost ProductId

    1 100 1

    2 200 1

    3 300 1

    4 400 1

    5 500 1

    6 600 1

    7 700 1

    1 100 2

    and so on

    Currently I insert the first 7 rows manually and then run the below query for every product id

    INSERT INTO dbo.Rate (LevelID, Cost, ProductId)

    SELECT LevelID, Cost, ProductId FROM dbo.Rate WHERE ProductId = 1

    Can you direct me on how to fully automate my work ?

  • Please see the first "Helpful Link" in my signature line below for tested scripts. 😉

    In the meantime, something like this untested script should do it for you.

    WITH cteLevel AS

    (

    SELECT TOP 7 N = ROW_NUMBER() OVER (ORDER BY (SELECT 1))

    FROM master.sys.all_columns

    )

    INSERT INTO dbo.Rate

    (LevelId, Cost, ProductId)

    SELECT LevelID = l.N

    ,Cost = l.N*100

    ,ProductID = l.p.ProductID

    FROM dbo.Product p

    CROSS JOIN cteLevel l

    ;

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

Viewing 2 posts - 1 through 1 (of 1 total)

You must be logged in to reply to this topic. Login to reply