xwpedram xwpedram - 5 months ago 50
SQL Question

T-Sql, Split string in the column and insert into table

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.

Answer

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