-3

I have a table with values as follows

StudentID | Name | Subscribed Subject |
101       |John  | Maths, Bio, Zoo    |
102       |Mary  | Bio, Zoo           |

I want to retrieve the information as follows

StudentID | Name | Subscribed Subject |
101       |John  | Maths              |
101       |John  | Bio                |
101       |John  | Zoo                |
102       |Mary  | Bio                |
102       |Mary  | Zoo                |

Can some one help me? Without using cursor.

Phil
  • 157,677
  • 23
  • 242
  • 245
vaduganathan
  • 141
  • 1
  • 1
  • 11

3 Answers3

1

Try this

Fiddle Demo

Create FUNCTION [dbo].[fn_Split](@text varchar(8000), @delimiter varchar(20))
RETURNS @Strings TABLE
(   
  position int IDENTITY PRIMARY KEY,
  value varchar(8000)  
)
AS
BEGIN

DECLARE @index int
SET @index = -1

WHILE (LEN(@text) > 0)
  BEGIN 
    SET @index = CHARINDEX(@delimiter , @text) 
    IF (@index = 0) AND (LEN(@text) > 0) 
      BEGIN  
        INSERT INTO @Strings VALUES (@text)
          BREAK 
      END 
    IF (@index > 1) 
      BEGIN  
        INSERT INTO @Strings VALUES (LEFT(@text, @index - 1))  
        SET @text = RIGHT(@text, (LEN(@text) - @index)) 
      END 
    ELSE
      SET @text = RIGHT(@text, (LEN(@text) - @index))
    END
  RETURN
END


select t.StudentID,t.Name ,test.value
from  tablename t cross apply fn_Split(t.SubscribedSubject,',') as test
0

try this code

      SET @STRSQL = 'SELECT ''' + REPLACE(Subscribed_Subject, ',',
                                                ''' ,''') + ''''

            DECLARE @tbl TABLE
                (
                  col1 VARCHAR(100) 

                )

insert your data to temp table then try to select from temp.

            INSERT  INTO @tbl
                    EXECUTE ( @STRSQL
                           )
Jayanti Lal
  • 1,175
  • 6
  • 18
0

You can achieve the functionality with below query.

SELECT A.[StudentID],  
     Split.a.value('.', 'VARCHAR(100)') AS String  
 FROM  (SELECT [StudentID],  
        CAST ('<M>' + REPLACE(Subscribed, ',', '</M><M>') + '</M>' AS XML) AS String  
        FROM  Student) AS A CROSS APPLY String.nodes ('/M') AS Split(a); 

For your quick reference, I am including the sql fiddle .

SQLFiddle

J-D
  • 1,575
  • 1
  • 11
  • 22