Professional Documents
Culture Documents
com/articles/cursor/72538/
Printed 2011/03/27 04:24PM
Introduction
Let's say we have a simple table of lookup values and that we want to get a list of these values into a simple comma
delimited character list. We can accomplish this with either a traditional CURSOR or a WHILE loop. However, listed
below is an easier way to produce the same list without having to use the infamous CURSOR.
Method
To illustrate this new approach, let's create a small table called MyStatus and load it with some sample entries.
Now let's load this table with some sample values using INSERT statements.
Now our objective is to create a list of comma delimited valid values, for example: Active,OnHold,Disabled,Closed
To get this list one would normally use a CURSOR (or a WHILE loop) as listed below:
OPEN myCursor
SET @MyStatusList = ''
FETCH NEXT FROM myCursor INTO @StatusDesc
WHILE @@FETCH_STATUS = 0
BEGIN
SET @MyStatusList = ISNULL(@MyStatusList,'') + @StatusDesc + ','
FETCH NEXT FROM myCursor INTO @StatusDesc
END
CLOSE myCursor
DEALLOCATE myCursor
Now, here is a simpler technique to get the same result without having to use a CURSOR (or a WHILE loop)
SET @MyStatusList = ''
SELECT @MyStatusList = ISNULL(@MyStatusList,'') + StatusDesc + ',' FROM MyStatus
If only distinct values are needed, then one must replace the above SELECT statement with the one below.
Finally drop the trailing comma at the end and then display.
Conclusion
In this article, we provided a simple way to get a comma delimited list from a table of entries without having to use a
CURSOR or a WHILE loop to read through the table. We also listed the actual T-SQL code to accomplish this task,
along with an example table and some sample entries.
Copyright © 2002-2011 Simple Talk Publishing. All Rights Reserved. Privacy Policy. Terms of Use. Report Abuse.