Groups | Blog | Home
all groups > sql server programming > february 2007 >

sql server programming : Creating cols out of rows



Ant
2/16/2007 11:54:00 PM
Hi, below is a not so elegant attempt at displaying 5 rows into a column for
each. I won't know how many rows there will be for the query so this must be
calucualted on the fly, thus I have used a cursor to do this.

Two questions. 1> Why is the concatinated string being used as the select
criteria being displayed as a string & how can I use this as a part of a
select stmnt.

2> is there, no, what is the more elegant way of doing this.

Thank you for any ideas on this:

Below is the script using northwind. The temp table is just for purposes of
display & not part of the solution.

Thanks in advance
Ant


use pubs

go

begin tran

create table #tempNames(
FName nvarchar(20)
)

insert #tempNames
select top 5 fname
from employee

declare myCursor cursor
for
select * from #tempNames

declare @s nvarchar(20)
declare @String nvarchar(100)

open myCursor

fetch from myCursor into @s

set @String = '''' + @s

while @@FETCH_STATUS = 0
begin
fetch from myCursor into @s
set @String = @String + ',' + '''' + @s + ''''
end

select @String
select 'Ant','Angie','Allen'

close myCursor
Deallocate myCursor
drop table #tempNames

commit tran

Alejandro Mesa
2/17/2007 8:51:00 AM
Concatenating row values in Transact-SQL
http://www.projectdmx.com/tsql/rowconcatenate.aspx


AMB


[quoted text, click to view]
AddThis Social Bookmark Button