Click here to Skip to main content
15,887,812 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a long string comma saperated and need to count no of commas in same
in sql server
please help
Posted

Hi,

Write a loop in SQL that loops through the string and makes use of CHARINDEX[^] and SUBSTRING[^], and then count the number of separators (till the end of the string).

Kind regards,
 
Share this answer
 
SQL
DECLARE @Ids NVARCHAR(255)
SET @Ids ='as,sdf,dsaf,sdfsd'

DECLARE @ID varchar(32), @Pos int , @commcount bigint


    SET @Ids = LTRIM(RTRIM(@Ids))+ ','
    SET @Pos = CHARINDEX(',', @Ids, 1)
SET @commcount=0
    IF REPLACE(@Ids, ',', '') <> ''
    BEGIN
        WHILE @Pos > 0
        BEGIN
            SET @ID = LTRIM(RTRIM(LEFT(@Ids, @Pos - 1)))
            IF @ID <> ''
            BEGIN
                SET @commcount = @commcount + 1
            END
            SET @Ids = RIGHT(@Ids, LEN(@Ids) - @Pos)
            SET @Pos = CHARINDEX(',', @Ids, 1)

        END
    END

select (@commcount-1)
 
Share this answer
 
One option is to use this:

SQL
Declare @string varchar(1000)
Set @string = 'a,b,c,d'
select len(@string) - len(replace(@string, ',', ''))


pl check the following thread for other options:

http://stackoverflow.com/questions/738282/how-do-you-count-the-number-of-occurrences-of-a-certain-substring-in-a-sql-varch[^]
 
Share this answer
 
i simply solved it as


select len('ddddddsdsgfgvddd')-len(replace('ddddddsdsgfgvddd','s',''))

It will count how many 's' occured in string
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900