Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Creating number of duplicates based on value

Author  Topic 

Neal44
Starting Member

17 Posts

Posted - 2010-06-14 : 07:53:16
Hi,

I have 2 SQL 2005 tables.

I need to create a number of duplicate records based on a column value.

Table_A contains 2 columns A_Code and Tests

Table_B also has an identical column named A_Code

If the A_Code value is the same in both tables I need to replicate the number of rows in Table_B based on the numeric value of the Tests column in Table_A (-1 as one row already exists).

Example

Table_A
A_Code Tests
0003 1
0005 2
0042 1
0913 3

Table_B
A_Code
0003
0005
0042
0913


The resulting rows in Table_B should be:

Table_B
A_Code
0003
0005
0005
0042
0913
0913
0913

Any ideas please?

Thanks in advance,


Neal

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2010-06-14 : 08:00:02
Something in this neighbourhood
-- Prepare sample data
DECLARE @TableA TABLE
(
Code CHAR(4) NOT NULL,
Tests TINYINT NOT NULL
)

INSERT @TableA
(
Code,
Tests
)
SELECT '0003', 1 UNION ALL
SELECT '0005', 2 UNION ALL
SELECT '0042', 1 UNION ALL
SELECT '0913', 3

DECLARE @TableB TABLE
(
Code CHAR(4) NOT NULL
)

INSERT @TableB
(
Code
)
SELECT '0003' UNION ALL
SELECT '0005' UNION ALL
SELECT '0042' UNION ALL
SELECT '0913'

-- Display initial state of TableB
SELECT *
FROM @TableB

-- Do the work
INSERT @TableB
(
Code
)
SELECT Code
FROM (
SELECT a.Code,
v.Number
FROM @TableA AS a
INNER JOIN master.dbo.spt_values AS v ON v.type = 'P'
WHERE v.Number BETWEEN 1 AND a.Tests

EXCEPT

SELECT Code,
ROW_NUMBER() OVER (PARTITION BY Code ORDER BY Code) AS Number
FROM @TableB
) AS d

-- Display current state of TableB
SELECT *
FROM @TableB



N 56°04'39.26"
E 12°55'05.63"
Go to Top of Page
   

- Advertisement -