Search code examples
sqlsql-servert-sqlcharindexpatindex

SQL query to get the multiple "," positions from a string


I have 5 rows of data like as below

Image 1

Now I need to find the position of every ',' from my input string.

My output should be like this:

Image 2


Solution

  • Please try this one it will give output as yours.

    Create table #Table (rowNo int identity(1,1), ID varchar(100))
    insert into #Table values('32132')
    insert into #Table values('32132,32132')
    insert into #Table values('32132,32132,6456,654,645')
    
    declare @TableRow int = (select count(*) from #Table),@Tableloop int = 1
    while(@Tableloop <= @TableRow)
    begin
        Declare @var varchar(100) ;
        SET @var = (select ID from #Table where rowNo=@Tableloop)
        declare @count int = (select len(@var) - len(replace(@var, ',', '')))
        declare @loop int = 1;
        declare @location int = 0;
        print 'Row' + cast(@Tableloop as varchar(5))
        while (@loop <= @count)
        begin
            SET @location = (select charindex(',',@var,@location))
            print cast(@loop as varchar(5)) + ' Comma at ' + cast(@location as varchar(5))
            SET @location = @location +1
            SET @loop = @loop + 1;
        end
    
        SET @Tableloop = @Tableloop + 1;
    END
    drop table #Table 
    

    This will show proper output just put it in temp table and display it.