Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sql Insert the same row multiple times

I'm trying to write a stored procedure which will take rows from a table like the one below

enter image description here

and insert them as many times as the value of the Quantity column. It should also assign a unique name & number to the rows inserted.

The end result should look something like the screenshot below

enter image description here

I can get very close to the what I want by the SQL below Source

INSERT INTO dbo. MyTable (....)
SELECT
    t1.Name + ' (' +   CAST(E.n as VARCHAR(3)) + ')',
    @Prefix + ' - ' + ROW_NUMBER () OVER (ORDER BY t1.Name )
FROM
    MyFirstTable t1
    JOIN ....
    JOIN .....
CROSS JOIN
    (SELECT TOP 500 ROW_NUMBER() OVER(ORDER BY (SELECT 1)) FROM sys.columns)E(n)
WHERE 
    E.n <= t1.Quantity
    AND....

The above statement works because I do know that quantity will never exceed 500 but I'm not a big fan of the way it is done. Is there a better way to accomplish this?

I'm not very experienced in sql.

like image 329
iDesi Avatar asked Nov 26 '25 12:11

iDesi


1 Answers

Seems like you have already figured out what you need for the most part. As far as the top 500 not exceeding goes, you could either leave it there or remove it. I think this is what you may be looking for:

SELECT
    id,        --not sure where this id comes from but looks different in your output
    CASE 
      WHEN E.n-1 > 0
        THEN t1.Name + ' (' +   CAST(E.n-1 as VARCHAR(3)) + ')'
     ELSE t1.Name
     END as  Name,
    @prefix + ' - ' + cast(ROW_NUMBER () OVER (ORDER BY t1.id) as varchar(10)) as Number
FROM
    test t1
    JOIN ...
    JOIN ...
CROSS JOIN
    (SELECT ROW_NUMBER() OVER(ORDER BY (SELECT 1)) FROM sys.columns)E(n)
WHERE 
    E.n <= t1.Quantity
    AND ....;

SQL Fiddle Demo

like image 92
FutbolFan Avatar answered Dec 01 '25 12:12

FutbolFan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!