Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Split string then insert new values into new table

I am trying to write a migration script to take one column of comma separated values and insert them individually into a new table in SQL server.

The current column is a list of email addresses and I am creating a new table to hold the collection of email addresses for each company.

I would assume I need to first split the string and then run through and INSERT statement for each entry in the array.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Maybe something like this…?

SELECT Id,  value
FROM Companies  
    CROSS APPLY STRING_SPLIT(Email, ',')

INSERT INTO emailAddresses(emailAddress, companyId)
VALUES (value, Id)

But I don’t know how to keep the INSERT statement running for all values.

>Solution :

Use insert...select.
First, create and populate sample table (Please save us this step in your future questions):

CREATE TABLE Companies  (
  Id int identity(1,1),
  Email nvarchar(4000)
);

INSERT INTO Companies(Email) VALUES
('A@gmail.com,B@gmail.com,C@gmail.com'),
('D@gmail.com,E@gmail.com,F@gmail.com'),
('G@gmail.com,H@gmail.com,I@gmail.com');

-- Target table
CREATE TABLE emailAddresses(
  emailAddress nvarchar(1000), 
  companyId int
);

Then, the insert statement:

INSERT INTO emailAddresses(emailAddress, companyId) 
SELECT value, Id
FROM Companies  
CROSS APPLY STRING_SPLIT(Email, ',');

A quick select to see the results:

SELECT * 
FROM emailAddresses

Results:

emailAddress    companyId
A@gmail.com     1
B@gmail.com     1
C@gmail.com     1
D@gmail.com     2
E@gmail.com     2
F@gmail.com     2
G@gmail.com     3
H@gmail.com     3
I@gmail.com     3

See a live demo on db<>fiddle

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading