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 2005 Forums
 Transact-SQL (2005)
 cursor??

Author  Topic 

kcrewjap
Starting Member

3 Posts

Posted - 2009-01-21 : 12:38:12
Hello,

i am new to T-SQL. i have a column in a table that has user names seperated by a comma (,) i have added new columns to the table so that each user can be placed in its own column from here on out. what i want help with is, how do i loop through the current rows and transfer the names in the comma seperated field into the new columns?

any help would be appreciated.

columns:
Member1 Member2 Member3 Member4 Member5 Member6

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2009-01-21 : 12:46:44
make use of parsevalues udf found here

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=115544

and use it like this

UPDATE t
SET t.Member1=r.Member1,
t.Member2= r.Member2,
t.Member3= r.Member3,
t.Member4= r.Member4,
t.Member5= r.Member5
FROM YourTable t
INNER JOIN
(
SELECT t1.IDcol,
MAX(CASE WHEN f.ID=1 THEN f.Val ELSE NULL END) AS Member1,
MAX(CASE WHEN f.ID=2 THEN f.Val ELSE NULL END) AS Member2,
MAX(CASE WHEN f.ID=3 THEN f.Val ELSE NULL END) AS Member3,
MAX(CASE WHEN f.ID=4 THEN f.Val ELSE NULL END) AS Member4,
MAX(CASE WHEN f.ID=5 THEN f.Val ELSE NULL END) AS Member5
FROM YourTable t1
CROSS APPLY dbo.ParseValues(t.usernamecol,',')f
GROUP BY t1.IDcol
)r
ON r.IDCol=t.IDCol

IDCol is the primary key of your table.



Go to Top of Page

harsh_athalye
Master Smack Fu Yak Hacker

5581 Posts

Posted - 2009-01-21 : 12:48:16
Rather than adding more columns for user name, it would be a good design if you could create a separate table for members and add a key from original table to member table as a foreign key.

As regards separating delimited values, you can use either of the split functions described in this thread: http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=50648

Harsh Athalye
India.
"The IMPOSSIBLE is often UNTRIED"
Go to Top of Page
   

- Advertisement -