Skip to content
Advertisement

SQL Select Value From Comma Delimited List

I have a field in my database called “Notes”. It contains a comma delimited list of values.

I want to perform a SELECT Query that only returns the first value in the “Notes” field.

This query would also return additional fields from the database.

for example

SELECT Name, Phone, Notes (only the first value)
FROM Table1 

Is this possible, and how do I do it?

Advertisement

Answer

You can use CHARINDEX with SUBSTRING:

SELECT Name, Phone, SUBSTRING(Notes, 1, CHARINDEX(',', Notes)) AS first_value
FROM Table1

Demo

DECLARE @csv varchar(50)
SET @csv = 'comma after this, and another,'

SELECT SUBSTRING(@csv, 1, CHARINDEX(',', @csv)) AS first_value

Result

|      first_value |
--------------------
| comma after this |

As mentioned in the comments, you should normalize your structure and not have more than one value stored in a single attribute.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement