Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
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.
In the following query:select 'John' as theName, 2unionselect 'Paul' as theName, 3unionselect 'Elvis' as theName, 4How do I extend the sql to interpret the number in the second column as an instruction as to how many times I want that row repeated? Without using a loop; just one set-based select statement.So the result would be:John 2John 2Paul 3Paul 3Paul 3Elvis 4Elvis 4Elvis 4Elvis 4
khtan
In (Som, Ni, Yak)
17689 Posts
Posted - 2008-07-09 : 07:15:32
[code]SELECT theName, cntFROM( SELECT 'John' AS theName, 2 AS cnt UNION SELECT 'Paul' AS theName, 3 UNION SELECT 'Elvis' AS theName, 4) dCROSS apply dbo.F_TABLE_NUMBER_RANGE (1, cnt) nORDER BYcnt/*theName cnt ------- ----------- John 2 John 2 Paul 3 Paul 3 Paul 3 Elvis 4 Elvis 4 Elvis 4 Elvis 4 (9 row(s) affected)*/[/code]KH[spoiler]Time is always against us[/spoiler]
coolerbob
Aged Yak Warrior
841 Posts
Posted - 2008-07-09 : 07:30:50
thanks! i knew it's been done before. just couldnt seem to find the right keywords to search on to get that thread
visakh16
Very Important crosS Applying yaK Herder
52326 Posts
Posted - 2008-07-09 : 07:38:07
you can do like this also:-
SELECT theName, cntFROM( SELECT 'John' AS theName, 2 AS cnt UNION SELECT 'Paul' AS theName, 3 UNION SELECT 'Elvis' AS theName, 4) dCROSS JOIN master..spt_values nwhere n.number<d.cntand n.type='p'ORDER BY cnttheName cnt------- -----------John 2John 2Paul 3Paul 3Paul 3Elvis 4Elvis 4Elvis 4Elvis 4