1

I have table like this

Name   |  Email             | Phone number 
alis     alis@123.com        +989355555;+989366666;+9803777777
John     john@yah.com        +989122222
sara     sara@yah.com        +989113212;+989113312

and I want a query to select this table like this and after that insert this table in other table.

Name   |  Email             | Phone number 
alis     alis@123.com        +989355555
alis     alis@123.com        +989366666
alis     alis@123.com        +9803777777
John     john@yah.com        +989122222
sara     sara@yah.com        +989113212
sara     sara@yah.com        +989113312

split all phone number and save them with similar fields name.

xwpedram
  • 467
  • 1
  • 8
  • 20
  • 1
    sql server 2016 introduced a built in string splitting function. If you are working with a lower version (and most of us are), read Aaron Bertrand's article about [string splitting functions.](http://sqlperformance.com/2012/07/t-sql-queries/split-strings) – Zohar Peled Jun 29 '16 at 08:00

1 Answers1

2

You can try this (using only T-SQL):

DECLARE @DataSource TABLE
(
    [Name] VARCHAR(12)
   ,[Email] VARCHAR(12)
   ,[PhoneNumber] VARCHAR(1024)
);

INSERT INTO @DataSource ([Name], [Email], [PhoneNumber])
VALUES ('alis', 'alis@123.com', '+989355555;+989366666;+9803777777')
      ,('John', 'john@yah.com', '+989122222')
      ,('sara', 'sara@yah.com', '+989113212;+989113312');

SELECT DS1.[Name]
      ,DS1.[Email]
      ,DS3.[value]
FROM @DataSource DS1
CROSS APPLY
(
    SELECT CAST(('<X>'+REPLACE(DS1.[PhoneNumber] ,';' ,'</X><X>')+'</X>') AS XML)
) DS2 ([Col])
CROSS APPLY
(
    SELECT T.C.value('.', 'varchar(32)') as value 
    FROM DS2.Col.nodes('X') as T(C)
) DS3 ([value]);

enter image description here

gotqn
  • 42,737
  • 46
  • 157
  • 243