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 2000 Forums
 Transact-SQL (2000)
 creating a comma delimitted file

Author  Topic 

jc
Starting Member

2 Posts

Posted - 2002-07-15 : 15:38:04
I need to create a comma delimitted file that would contain the person id from table a and then all of that person's order id's from table b so that it will look like the following:

PersonID1, OrderId1, OrderId2, OrderId3
PersonID2, OrderId4, OrderId5
PersonID3, OrderId6, OrderId7, OrderId8

I can create a cursor that fetches the personid from table a and then uses an inner cursor to fetch the orderid's for that person from table b - however I can't figure out how to get it to print out horizontally like above in one line. Thanks



Page47
Master Smack Fu Yak Hacker

2878 Posts

Posted - 2002-07-15 : 15:55:55
here is a set-based method that utilizies the @variable = column = expression syntax of an UPDATE statement to avoid the ugly cursor...



--ddl
drop table orders
drop table persons
go
create table persons (pk varchar(10) primary key)
create table orders ([order] varchar(10) primary key, person varchar(10) constraint fk references persons(pk))
go

--sample data
insert persons(pk)
select 'PersonID1'
union select 'PersonID2'
union select 'PersonID3'
go

insert orders(person,[order])
select 'PersonID1','OrderID1'
union select 'PersonID1','OrderID2'
union select 'PersonID1','OrderID3'
union select 'PersonID2','OrderID4'
union select 'PersonID2','OrderID5'
union select 'PersonID3','OrderID6'
union select 'PersonID3','OrderID7'
union select 'PersonID3','OrderID8'
go

--create a temp table to work with
select
person,
[order],
space(8000) as list
into
#workingtable
from
persons p inner join orders o
on p.pk = o.person
order by
person,
[order]

--some variables
declare @list varchar(8000), @lastperson varchar(10)
select @list = '', @lastperson = ''

--build the list column of the temp table
update #workingtable
set
@list = list = case
when @lastperson <> person then person + ', ' + [order]
else @list + ', ' + [order]
end,
@lastperson = person

--return the csv
select
max(list)
from
#workingtable
group by
person

drop table #workingtable
go

 


<O>
Go to Top of Page

jc
Starting Member

2 Posts

Posted - 2002-07-16 : 10:41:48
Thank you - that is exactly what I was looking for.

Go to Top of Page
   

- Advertisement -