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?
views:
1821answers:
5
+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
2009-04-10 17:31:49
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
2010-05-25 15:55:40
+1
A:
You can compare the length of the string with one where the commas are removed:
len(value) - len(replace(value,',',''))
Guffa
2009-04-10 17:33:00
+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
2009-04-10 18:16:53
+1 for thinking of that. It's what I usually start with when someone uses comma separated data in a field.
Guffa
2009-04-10 20:03:21
Part of the purpose of this question was to take existing data like that and split it apart appropriately.
Orion Adrian
2010-06-03 18:34:52
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
2009-04-11 21:08:59
+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
2010-05-25 15:57:16