Need to generate n rows based on a value in a column
I'll assume
- MyRef etc is a column in TableA
- You have a numbers table
Something like:
SELECT * INTO #TableA
FROM
(
SELECT 1 AS ID, 3 AS QUANTITY, 'MyRef' AS refColumn
UNION ALL
SELECT 2, 2, 'AnotherRef'
) T
;WITH Nbrs ( Number ) AS (
SELECT 1 UNION ALL
SELECT 1 + Number FROM Nbrs WHERE Number < 99
)
SELECT
A.ID, A.refColumn + CAST(N.Number AS varchar(10))
FROM
#TableA A
JOIN
Nbrs N ON N.Number <= A.QUANTITY
This would also do the trick. It uses recursion, creates a table with rows 1-100.
WITH NBR ( NUM ) AS (
SELECT 1 UNION ALL
SELECT 1 + NUM FROM NBR
WHERE NUM < 100
)
SELECT * into NUMBERS from NBR
This will create the number of rows you want, in SQL Server 2005+, though I'm not sure exactly how you want to determine what MyRef and AnotherRef should be...
WITH
expanded
AS
(
SELECT id, Quantity FROM myTable
UNION ALL
SELECT id, Quantity - 1 FROM expanded WHERE Quantity > 1
)
SELECT
*,
ROW_NUMBER() OVER (ORDER BY id, Quantity) AS unique_ref
FROM
expanded
ORDER BY
id,
Quantity