Groups | Blog | Home
all groups > sql server (microsoft) > february 2007 >

sql server (microsoft) : Quickly convert a single column table to a string?


mark4asp
2/23/2007 10:04:03 AM
Is there a convenient way to convert a small single column table of
zero to six rows of VarChar(50) data to a single string via a
function. Each item is ideally separated by semi-colon space.

Do I need to use a cursor to do this?
Steve
2/23/2007 5:00:58 PM
[quoted text, click to view]

--SQL SERVER 2005
DECLARE @str varchar(4000)
SET @str = (SELECT d.name + ','
FROM HumanResources.Department d
ORDER BY d.name
FOR XML PATH(''))
SET @str = SUBSTRING(@str,1,LEN(@str)-1)
SELECT @str

--SQL SERVER 2000
DECLARE @name varchar(50)
DECLARE @str varchar(4000)
SET @str = ''
DECLARE Build CURSOR
LOCAL
FORWARD_ONLY
FOR
SELECT d.name
FROM HumanResources.Department d
ORDER BY d.name
OPEN Build
FETCH NEXT FROM Build INTO @name
WHILE @@FETCH_STATUS = 0
BEGIN
SET @str = @str + @name + ','
FETCH NEXT FROM Build INTO @name
END
CLOSE Build
DEALLOCATE Build
SET @str = SUBSTRING(@str,1,LEN(@str)-1)
SELECT @str
mark4asp
2/26/2007 2:59:11 AM
[quoted text, click to view]

This almost works but it wraps each item in XML tags which then need
to be removed:
DECLARE @str varchar(4000)
SET @str = ( SELECT Activity FROM ActivityTypeTable ORDER BY Activity
FOR XML PATH('') )
SET @str = replace (@str, '</Activity><Activity>', '; ')
SET @str = replace (@str, '</Activity>', '')
SET @str = replace (@str, '<Activity>', '')
SELECT @str

Or more cryptically:

DECLARE @str varchar(4000)
SET @str = ( SELECT Activity FROM ActivityTypeTable ORDER BY Activity
FOR XML PATH('') )
SELECT replace (replace (replace (@str, '</Activity><Activity>', ';
'), '</Activity>', ''), '<Activity>', '')


[quoted text, click to view]

I bet this second one actually takes less time !


Thanks Steve
Steve
2/26/2007 8:34:09 AM
[quoted text, click to view]

This is the output I see:
Document Control,Engineering,Executive,Facilities and
Maintenance,Finance,Human Resources,Information
Services,Marketing,Production,Production Control,Purchasing,Quality
Assurance,Research and Development,Sales,Shipping and Receiving,Tool
Design
AddThis Social Bookmark Button