Atlanta Custom Software Development 

 
   Search        Code/Page
 

User Login
Email

Password

 

Forgot the Password?
Services
» Web Development
» Maintenance
» Data Integration/BI
» Information Management
Programming
  Database
Automation
OS/Networking
Graphics
Links
Tools
» Regular Expr Tester
» Free Tools


Click here to copy the following block
create table #temp (
rowid int primary key, rowname char(10), repeat_times int
);
insert into #temp values (1,'aaa',1);
insert into #temp values (2,'bbb',5);
insert into #temp values (3,'ccc',1);
insert into #temp values (4,'ddd',2);
select * from #temp;
/*
rowid    rowname  repeat_times
----------- ---------- ------------
     1 aaa          1
     2 bbb          5
     3 ccc          1
     4 ddd          2
*/

-- Objective:
-- To generate duplicates of each row based on the value
-- in repeat_times column. This example assumes that the
-- value is less than or equal to 5 only.
SELECT t1.*
FROM #temp AS t1
JOIN (
SELECT 1 AS cnt
UNION ALL
SELECT 2
UNION ALL
SELECT 3
UNION ALL
SELECT 4
UNION ALL
SELECT 5
) AS t2
ON t2.cnt <= t1.repeat_times
ORDER BY t1.rowid , t1.rowname , t1.repeat_times;
/*
rowid    rowname  repeat_times
----------- ---------- ------------
     1 aaa          1
     2 bbb          5
     2 bbb          5
     2 bbb          5
     2 bbb          5
     2 bbb          5
     3 ccc          1
     4 ddd          2
     4 ddd          2
*/


-- Generic solution using a Numbers table
SELECT t1.*
FROM #temp AS t1
JOIN Numbers AS t2
ON t2.Number > 0 And t2.Number <= t1.repeat_times
ORDER BY t1.rowid , t1.rowname , t1.repeat_times;


Submitted By : Nayan Patel  (Member Since : 5/26/2004 12:23:06 PM)

Job Description : He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting.
View all (893) submissions by this author  (Birth Date : 7/14/1981 )


Home   |  Comment   |  Contact Us   |  Privacy Policy   |  Terms & Conditions   |  BlogsZappySys

© 2008 BinaryWorld LLC. All rights reserved.