I have a table that looks like the following:
╔══════════╦═══════════╦════════╦
║ SO ║ SO_Line ║ ... ║
╠══════════╬═══════════╣════════║
║ ABC ║ 1 ║ ║
║ ABC ║ 3 ║ ║
║ ABC ║ 5 ║ ║
║ DEF ║ 1 ║ ║
║ DEF ║ 2 ║ ║
╚══════════╩═══════════╝════════╝
What I'd like to do is duplicate a result set (x) amount of times. For instance, given this result set: SELECT * FROM Table WHERE SO = 'ABC'
, I'd like to duplicate that result set 10 times. Basically I want to keep all of the data in all of the other columns the same, but I'll change the primary key to be something else (for instance, ABC-1
). My final table after duplicating that set would be like this:
╔══════════╦═══════════╦════════╦
║ SO ║ SO_Line ║ ... ║
╠══════════╬═══════════╣════════║
║ ABC ║ 1 ║ ... ║
║ ABC ║ 3 ║ ... ║
║ ABC ║ 5 ║ ... ║
║ ABC-1 ║ 1 ║ ... ║
║ ABC-1 ║ 3 ║ ... ║
║ ABC-1 ║ 5 ║ ... ║
╚══════════╩═══════════╝════════╝
Normally the way I would do this is by inserting the records from the result set into a temporary table and then assigning a row number to each row. Then I'd iterate through the temporary table using something like WHILE @i < @RowCount
and do an insert into the main table using @i
to increment the PK. I'm basically asking if A) that's the most reasonable way to accomplish this, and if not, B) is there a more efficient way of handling this?
Best Answer
You can get it using a table value or a value list, and a CROSS JOIN.
dbfiddle here
Instead of use a value list, you could use an INLINE User defined function like this:
Then convert your query to:
NOTE: I've used
tvValues(7)
but you can use other values.This is the result:
dbfiddle here