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)
 combining string fields

Author  Topic 

hobbes
Starting Member

3 Posts

Posted - 2005-05-19 : 06:46:17
Hi
i've got a problem which i'm not sure is possible, but you guys worked your magic last time so i thought i'd try and test you again!

i've got a table holding a list of peoples qualifications. however, some people have multiple instances of the same qualification but different notes. i want to combine the notes field to reduce the number of rows from many to one.

Example of what it currently is:
Name Qual Notes
Simon spanish Distinction
Simon spanish Pass
Simon german A Level
Stewart spanish Degree
Stewart spanish 2:1
Mrtin english A level

This is what i want it to look like:
Name Qual Notes
Simon spanish Distinction Pass A level
Simon german A Level
Stewart spanish Degree 2:1
Martin english A level

i was trying to find some kind of grouping function, but without success. my only alternative would be to use a cursor to step through the records.
is there a better way?

any help would be gratefully received!
Simon

Seventhnight
Master Smack Fu Yak Hacker

2878 Posts

Posted - 2005-05-19 : 08:41:27
This should do it, but be careful with the delete at the end.


Create Table #myTable (name varchar(10), Qual varchar(10), notes varchar(100), allNotes varchar(100))
Insert Into #myTable (name, Qual, notes)
Select 'Simon', 'spanish', 'Distinction' Union
Select 'Simon', 'spanish', 'Pass' Union
Select 'Simon', 'german', 'A Level' Union
Select 'Stewart', 'spanish', 'Degree' Union
Select 'Stewart', 'spanish', '2:1' Union
Select 'Martin', 'english', 'A level'

Select * From #myTable

Declare @curKey varchar(100),
@Notes varchar(100)

Update #myTable
Set
@Notes = case when isnull(@curKey,'')<>name+'|'+Qual then notes else @notes + ', ' + notes end,
@curKey = name+'|'+Qual,
AllNotes = @notes
From #myTable

Delete A
From #myTable A
Where len(Allnotes)<(Select max(len(Allnotes)) From #myTable B Where name = A.name and Qual = A.Qual)

Select * From #myTable

Drop Table #myTable


Corey

Secret Service Agent: Mr. President, you're urinating on me.
President Lyndon Johnson: I know I am. It's my prerogative.
Go to Top of Page
   

- Advertisement -