tags:

views:

1821

answers:

5

I have a column that has values formatted like a,b,c,d. Is there a way to count the number of commas in that value in T-SQL?

+10  A: 

The first way that comes to mind is to do it indirectly by replacing the comma with an empty string and comparing the lengths

Declare @string varchar(1000)
Set @string = 'a,b,c,d'
select len(@string) - len(replace(@string, ',', ''))
cmsjr
That answers the question as written in the text, but not as written in the title.To make it work for more than one character, just need to add a / len(searchterm) round the thing. Posted an answer in-case it's useful for someone.
Andrew Barrett
+1  A: 

You can compare the length of the string with one where the commas are removed:

len(value) - len(replace(value,',',''))
Guffa
+2  A: 

Perhaps you should not store data that way. It is a bad practice to ever store a comma delimited list in a field. IT is very inefficient for querying. This should be a related table.

HLGEM
+1 for thinking of that. It's what I usually start with when someone uses comma separated data in a field.
Guffa
Part of the purpose of this question was to take existing data like that and split it apart appropriately.
Orion Adrian
A: 
DECLARE @records varchar(400)
SELECT @records = 'a,b,c,d'
select  LEN(@records) as 'Before removing Commas' , LEN(@records) - LEN(REPLACE(@records, ',', '')) 'After Removing Commans'
Shiva
+3  A: 

Quick extension of cmsjr's answer that works for strings of more than more character.

CREATE FUNCTION dbo.CountOccurancesOfString
(
    @searchString nvarchar(max),
    @searchTerm nvarchar(max)
)
RETURNS INT
AS
BEGIN
    return (LEN(@searchString)-LEN(REPLACE(@searchString,@searchTerm,'')))/LEN(@searchTerm)
END

Usage:

SELECT * FROM MyTable
where dbo.CountOccurancesOfString(MyColumn, 'MyString') = 1
Andrew Barrett