Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql multiple insert on one table, while looping/iterating over another table?

I have two table "TempStore" and "Store" with the same column called "Items".

There is data in "TempStore" table which I need to move over to "Store" table which requires few modifications.

I need to iterate over "TempStore" data (i.e. items) and insert into Store...

More specifically: How can I iterate over TempStore (in sql) where "for each item in 'TempStore' I need to store 2 or maybe 3 items in 'Store' with little modification", how can I accomplish this?

What I want to do is take each rowdata from "[SELECT * FROM TempStore]" and insert three records in "Store" with being able to change "items"

like image 220
VoodooChild Avatar asked Dec 10 '22 15:12

VoodooChild


1 Answers

try INSERT-SELECT:

INSERT INTO Store
        (col1, col2, col3...)
    SELECT
        col1, col2, col3...
        FROM TempStore
        WHERE ...

just make the SELECT return one row for every insert, and produce the values in the Cols that you need. You might need CASE and a join to another table to make the extra rows.

EDIT based on comments, OP wanted to see the numbers table in action

Lets say TempStore table has {Items, Cost, Price, ActualCost, ActualPrice} But in the Store table I need to store {Items, Cost, Price}. The ActualCost and ActualPrice from TempStore datarow would need to be added as another row in Store....(I hope this makes sense)....Anyways, is the solution using "WHILE-BEGIN-END"??

CREATE TABLE Numbers (Number int NOT NULL PRIMARY KEY)
INSERT INTO Numbers VALUES(1)
INSERT INTO Numbers VALUES(2)
INSERT INTO Numbers VALUES(3)


INSERT INTO Store
        (Items, Cost, Price)
    SELECT
        t.Items, t.Cost
            ,CASE
                 WHEN n.Number=1 THEN t.Price
                 WHEN n.Number=2 THEN t.ActualCost
                 ELSE t.ActualPrice
             END
        FROM TempStore         t
            INNER JOIN Numbers N ON n.Number<=3
        WHERE ...

you could even use a UNION:

INSERT INTO Store
        (Items, Cost, Price)
    SELECT
        t.Items, t.Cost, t.Price
        FROM TempStore t
    UNION ALL
    SELECT
        t.Items, t.Cost, t.ActualCost
        FROM TempStore t
    UNION ALL
    SELECT
        t.Items, t.Cost, t.ActualPrice
        FROM TempStore t

either the Numbers table or the UNION will we WAY better than a loop!

like image 83
KM. Avatar answered Jan 14 '23 06:01

KM.