Friday, March 30, 2012

Query help

Hi,
I have a single row in a table:

Title Desc Quantity
----------
aaaa bbbbb 4

and I need the query to insert "Qty" number of records into a second table, e.g

Title1 Desc1
------
aaaa bbbbb
aaaa bbbbb
aaaa bbbbb
aaaa bbbbb

I reckon its some sort of self join but any help would be appreciated.

gregFor the example below I use a function, but you can also use any table that contains sequencial numbers with no gaps. A table with IDENTITY field that did not have any deletes would do.

set nocount on
create table t1 (
title char(4) not null,
[desc] varchar(50) not null,
quantity int not null)
go
create table t2 (
title1 char(4) not null,
desc1 varchar(50) not null)
go
insert t1 values ('aaaa', 'bbbbb', 4)
insert t1 values ('bbbb', 'ccccc', 1)
insert t1 values ('cccc', 'ddddd', 3)
insert t1 values ('dddd', 'eeeee', 2)
insert t1 values ('eeee', 'fffff', 5)
go
insert t2
select title, [desc] from dbo.fn_CartesianProduct() f
inner join t1 on f.[id] < t1.quantity order by 1
go
drop table t1, t2
go|||Excellent - I have an Integers table that substitutes nicely.
Thanks.

No comments:

Post a Comment