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)
 SQL Query Help

Author  Topic 

Ventura1
Starting Member

2 Posts

Posted - 2005-12-19 : 12:28:48
Hello,

I have a simple view that holds a Booking ID and a Description of the Catering booked for it on an individual basis. An example of the data retrieved from a select query is shown below...

SELECT [ID], [Description] FROM vwBookedCatering

ID Description
--- ------------
754 Coffee
754 Tea
754 Water
755 Coffee
755 Tea
755 Water
756 Coffee
756 Tea

What I want to do with the data is show all of the booked catering details for each booking on a single row, for example...

ID FullDescription
--- ----------------
754 Coffee, Tea, Water
755 Coffee, Tea, Wate
756 Coffee, Tea

Could anyone help me with this?

TG
Master Smack Fu Yak Hacker

6065 Posts

Posted - 2005-12-19 : 12:47:42
do a site search on "csv" for lots of discussion about this but here is the jist:

you can run this code as is to see the results:

use pubs
go

create view vwBookedCatering
as

select 754 [id], 'Coffee' [description] union all
select 754, 'Tea' union all
select 754, 'Water' union all
select 755, 'Coffee' union all
select 755, 'Tea' union all
select 755, 'Water' union all
select 756, 'Coffee' union all
select 756, 'Tea'

go

--Create a function that returns the comma seperated values for a given ID
create function dbo.BookingsById(@id int)
returns varchar(8000)
as
begin
declare @out varchar(8000)
select @out = coalesce(@out + ', ' + [description], [description])
from vwBookedCatering
where [id] = @id

return @out
end
go


--Use the function
select [id]
,dbo.BookingsById([id]) [Bookings]
from (select distinct [id] from vwBookedCatering) a

go
drop function dbo.BookingsById
drop view vwBookedCatering


Be One with the Optimizer
TG
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2005-12-20 : 00:25:47
And here is the reason why Function is to be used
http://sqljunkies.com/WebLog/amachanic/archive/2004/11/10/5065.aspx?Pending=true

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

Ventura1
Starting Member

2 Posts

Posted - 2005-12-20 : 04:33:28
That is fantastic, I have needed to do this on a couple of occassions recently and this is exactly what I have been looking for!

I am going to read that article so I understand excatly what the function is doing because at the moment I can't figure out how it works.

Thanks guys!
Go to Top of Page
   

- Advertisement -