Using recursion and borrowing Michael Fredrickson installation code:
declare @T table (
Name varchar(50),
Sales int
)
insert into @T values ('Stella', '2')
insert into @T values ('Jennifer', '2')
insert into @T values ('Greg', '3')
;with People (Name, Sales) as
(
select Name, Sales
from @T
union all
select Name, Sales - 1
from People
where Sales - 1 > 0
)
select Name, 1 as Quantity
from People
option (maxrecursion 0)
It seems to work faster on my mailbox (5 times faster than Michael Fredrickson according to the query plan, but with a lot more logical readings), but this is not so important.
source
share