Click here to Skip to main content
15,849,829 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a table in sql server in which one column has comma seprated values, i want to generate a new row for each comma seprated value. For ex.

Table :

    col1    col2   col3
     1       45     7
     2       48     6,7
     3       46     4

output should be :

    col1    col2   col3
     1       45     7
     2       48     6
     2       48     7
     3       46     4

Thanks in advance.
Updated 18-May-12 11:54am
OriginalGriff 18-May-12 4:21am    
And what have you tried?
Where are you stuck?
bhagirathimfs 18-May-12 4:22am    
While inserting to the table do this.
means insert into table for each value
Example:now you are inserting like this
col1 =1 col2=45 and col3=6,7
now insert into table like this
col1=1 col2=45 col3=6
than insert again
col1=2 col2=25 col=7
Ashwani Dhiman 18-May-12 4:33am    
I have to compare the value of Col3 which is comma seprated. These tables are created previously with this structure, thats why i thought to break these value in rows.
Jim Jos 18-May-12 4:27am    
Are you trying to do it with Store Proc or .NET code? .NET would be easier..
Ashwani Dhiman 18-May-12 4:35am    
Store Proc

hi, use this code to split the value and write a stored procedure to store,

Create FUNCTION [dbo].[fn_Split] (@list nvarchar(MAX))  
   RETURNS @tbl TABLE (number int NOT NULL) AS  
   DECLARE @pos        int,  
           @nextpos    int,  
           @valuelen   int  
   SELECT @pos = 0, @nextpos = 1  
   WHILE @nextpos > 0  
      SELECT @nextpos = charindex(',', @list, @pos + 1)  
      SELECT @valuelen = CASE WHEN @nextpos > 0  
                              THEN @nextpos  
                              ELSE len(@list) + 1  
                         END - @pos - 1  
      INSERT @tbl (number)  
         VALUES (convert(int, substring(@list, @pos + 1, @valuelen)))  
      SELECT @pos = @nextpos  
-- Select * from dbo.fn_Split('1,2,3')
Share this answer
Maciej Los 18-May-12 17:26pm    
Good work, 5!
S.P.Tiwari 22-May-12 5:48am    
Please see this reference[^] where answer to a similar question is given.
Share this answer
Wendelius 18-May-12 17:00pm    
Good link!
VJ Reddy 18-May-12 20:27pm    
Thank you, Mika :)
Maciej Los 18-May-12 17:26pm    
Good link, +5!
VJ Reddy 18-May-12 20:28pm    
Thank you, losmac :)

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