troubleshooting Question

Merge columns from multiple rows into one field problem

Avatar of mawdryn
mawdryn asked on
Microsoft SQL Server
6 Comments1 Solution312 ViewsLast Modified:
Hi,

I'm trying to combine data from one column on multiple rows into one field in MS SQL 2000.

ie,

From:
Accountno Reference
1234          ABC
1234          DEF
1234          GHI
2345          SDF
2345          AAA

into:
Accountno Reference
1234          ABC, DEF, GHI
2345          SDF, AAA

I have created a function to do this based on my google searches, however it will always return a null.
I'm not even sure if this is the best way to go about it, noting that there are thousands of such records.

Code for the function is as follows:

create function dbo.concatinstruments(@accountno varchar)
returns varchar(100)
as
begin
    declare @output varchar(100)
    select @output = coalesce(@output+', ','') + reference
    from instrumentview
    return @output
end

^ This doesn't work for some reason (I'm not a SQL expert)

however the following code (not a function) does work.,

declare @accountno varchar(100)
set @accountno = '1234'
declare @output varchar(100)
select @output = calesce(@output+', ','') + reference from instruments where accountno = @accountno
select accountno,@output from instruments where accountno = @accountno group by accountno

Am I calling the function wrong? I've never really dealt with functions before, so I'm dumb as a post on this.
Any help appreciated, Thanks.
ASKER CERTIFIED SOLUTION
HuyBD

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Log in to continue reading
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform for $9.99/mo
View membership options
Unlock 1 Answer and 6 Comments.
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
The Value of Experts Exchange in My Daily IT Life

Experts Exchange (EE) has become my company's go-to resource to get answers. I've used EE to make decisions, solve problems and even save customers. OutagesIO has been a challenging project and... Keep reading >>

Mike

Owner of Outages.IO
Phoenix, Arizona, United States
Member Since 2016
Join a full scale community that combines the best parts of other tools into one platform.
Unlock 1 Answer and 6 Comments.
View membership options
“All of life is about relationships, and EE has made a virtual community a real community. It lifts everyone's boat.”
William Peck

Member since 2004