SQLServerCentral Article

A simple T-SQL statement to create a list of lookup values

,

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.

CREATE TABLE [dbo].[MyStatus](
 [Status_Id] [int] IDENTITY(1,1) PRIMARY KEY NOT NULL,
 [StatusDesc] [varchar](25) NULL,
)

Now let's load this table with some sample values using INSERT statements.

INSERT INTO MyStatus VALUES ('Active')
INSERT INTO MyStatus VALUES ('OnHold')
INSERT INTO MyStatus VALUES ('Disabled')
INSERT INTO MyStatus VALUES ('Closed')

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:

/*--------------- CURSOR approach --------------- */DECLARE @MyStatusList VARCHAR(1000)
DECLARE @StatusDesc VARCHAR(25)
DECLARE myCursor CURSOR FOR SELECT StatusDesc FROM MyStatus
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
/* drop the trailing delimiter and display */SET @MyStatusList = SUBSTRING(@MyStatusList, 1, LEN(@MyStatusList)-1) 
SELECT @MyStatusList
/*--------------- End of CURSOR approach --------------- */

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.

SELECT @MyStatusList = ISNULL(@MyStatusList,'') + StatusDesc + ',' 
 FROM (SELECT DISTINCT StatusDesc FROM MyStatus) x

Finally drop the trailing comma at the end and then display.

SET @MyStatusList = SUBSTRING(@MyStatusList, 1, LEN(@MyStatusList)-1) 
SELECT @MyStatusList

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.

Resources

Rate

3.63 (177)

You rated this post out of 5. Change rating

Share

Share

Rate

3.63 (177)

You rated this post out of 5. Change rating