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

sql server (microsoft) : String Concatinating Within Fetch Loop


Nate.Strack NO[at]SPAM gmail.com
2/23/2006 8:06:49 AM
Ok i'm trying to make a list of names in one var something like this
DECLARE @NAME_LIST VARCHAR(5000)
DECLARE @NAME VARCHAR(30)

DECLARE NAMES CURSOR FOR
SELECT FIRSTNAME FROM MAIN_NAMES

OPEN NAMES
FETCH NEXT FROM NAMES
INTO @NAME
WHILE @@FETCH_STATUS = 0
BEGIN
SET @NAME_LIST = RTRIM(@NAME_LIST) + ',' + RTRIM(@NAME)
FETCH NEXT FROM NAMES
INTO @NAME

CLOSE NAMES
DEALLOCATE NAMES

PRINT @NAME_LIST

SO I SHOULD BE TURNING A TABLE LIKE
name1
name2
name3
name4 into
a varchar like
name1,name2,name3,name3

when you print @name_list is just is blank i don't get it anyone have
some insite?
Barry
2/23/2006 9:49:38 AM
Hmm maybe because you haven't set @NAME_LIST = '' first.

I'm pretty sure @NAME_LIST will be NULL - and if you add a string to a
NULL it produces NULL.

However, I wouldn't use this method. Cursors are not a very good
practice in SQL Server. This kind of thing should be done at the
Client side rather than the Server.

If you really want to do it on the Server though check out this web
site for other potential solutions..

http://www.aspfaq.com/show.asp?id=2529

HTH

Barry
SQL
2/23/2006 10:54:44 AM
You don't need a cursor, all you need is this
DECLARE @NAME_LIST VARCHAR(5000)
SELECT @NAME_LIST = ''
SELECT @NAME_LIST =@NAME_LIST + RTRIM(FIRSTNAME) + ',' FROM MAIN_NAMES
select left(@NAME_LIST,
Len(@NAME_LIST) -1)

Here is an example that you can run in the pubs database and then you
can modify your code

use pubs
DECLARE @NAME_LIST VARCHAR(5000)
SELECT @NAME_LIST = ''
SELECT @NAME_LIST =@NAME_LIST + RTRIM(au_fname) + ',' FROM authors
where au_fname like 'a%'
select @NAME_LIST
select left(@NAME_LIST,
Len(@NAME_LIST) -1) -- get rid of last comma


http://sqlservercode.blogspot.com/
Nate.Strack NO[at]SPAM gmail.com
2/23/2006 12:02:33 PM
Thanks you so much that worked beatifully..
Madhivanan
2/24/2006 5:50:56 AM
AddThis Social Bookmark Button