Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Need to transform single column into a row 1

Status
Not open for further replies.

RikHess

MIS
Jul 25, 2002
69
US
I have a need to present a column of data as a single row field.

For example if a query returns a single column with 3 row values:

rec1='AAA'
rec2='BBB'
rec3='CCC'

I want to present it as:

rec='AAA; BBB; CCC'

How can this be done?

Ideally I would like to have this coded in a function.

Thanks for any help.

 
Code:
DECLARE @lcString varchar(8000)
SET @lcString = ''
SELECT @lcString = @lcString + FieldName + ';'

SELECT LEFT(@lcString, LEN(@lcString)-1)
not tested

Borislav Borissov
VFP9 SP2, SQL Server 2000/2005.
 
Here's an example. Copy and paste this into Management Studio/Query Analyzer and execute. Modify and apply to your data.
Code:
DECLARE @T1 TABLE (Column1 VARCHAR(10))
INSERT INTO @T1 SELECT 'AAA'
INSERT INTO @T1 SELECT 'BBB'
INSERT INTO @T1 SELECT 'CCC'

SELECT * FROM @T1

DECLARE @Vals VARCHAR(8000)

SELECT @Vals = ''

SELECT @Vals = @Vals + Column1 + '; '   FROM @T1
IF LEN(@Vals) > 1 SELECT @Vals = SUBSTRING(@Vals, 1, LEN(@Vals) - 1)

SELECT @Vals
 
RiverGuy and Borislav,

That did the trick!
Thanks.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top