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
 SQL Server Development (2000)
 display data horizontally

Author  Topic 

scabral7
Yak Posting Veteran

57 Posts

Posted - 2010-04-16 : 14:17:12
sql 2000:

Have this in Table:
A 2ZS
A RRT
A ABC
B 22R
B 123
C WWW

Need this in query result:
A 2ZS, RRT, ABC
B 22R, 123
C WWW

any ideas?

thanks
scott

hanbingl
Aged Yak Warrior

652 Posts

Posted - 2010-04-26 : 14:21:02
does it return a list in string or columns?

quote:
Originally posted by scabral7

sql 2000:

Have this in Table:
A 2ZS
A RRT
A ABC
B 22R
B 123
C WWW

Need this in query result:
A 2ZS, RRT, ABC
B 22R, 123
C WWW

any ideas?

thanks
scott

Go to Top of Page

hanbingl
Aged Yak Warrior

652 Posts

Posted - 2010-04-26 : 14:56:48
Anyone knows a better way of doing this than a cursor??


declare @t1 table(c1 char(1), c2 char(5))
insert into @t1
select 'A','2ZS'
UNION ALL
SELECT 'A','RRT'
UNION ALL
SELECT 'A','ABC'
UNION ALL
SELECT 'B','22R'
UNION ALL
SELECT 'B','123'
UNION ALL
SELECT 'C','WWW'

declare @c1 char(1)
declare @liststr varchar(8000)
declare crs cursor
for select distinct c1 from @t1

select @c1 as c1, @liststr as c2 into #t1 where 1=2

open crs
fetch next from crs into @c1

while @@fetch_status = 0
begin
select @liststr=coalesce(@liststr+',', '')+c2 from @t1 where c1 = @c1
insert into #t1 values(@c1, @liststr)
set @liststr = null
fetch next from crs into @c1
end
select * from #t1
drop table #t1

close crs
deallocate crs
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2010-04-27 : 00:59:37
yup..see below


--test table
create table
test1
(c1 char(1), c2 varchar(5))
insert into test1
select 'A','2ZS'
UNION ALL
SELECT 'A','RRT'
UNION ALL
SELECT 'A','ABC'
UNION ALL
SELECT 'B','22R'
UNION ALL
SELECT 'B','123'
UNION ALL
SELECT 'C','WWW'


--udf to concat values
CREATE FUNCTION ConcatValues
(@c1 char(1)
)
RETURNS varchar(8000)
AS
BEGIN
DECLARE @ret varchar(8000)

SELECT @ret=COALESCE(@ret+',','') + c2
FROM test1
WHERE c1=@c1

RETURN @ret
END


--the solution using call to above udf
SELECT DISTINCT c1,dbo.ConcatValues(c1) AS ValList
FROM test1


--remove table created after test
drop table test1


output
-------------------------------
c1 ValList
A 2ZS,RRT,ABC
B 22R,123
C WWW



------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -