Avatar of Andy Green
Andy Green
Flag for United Kingdom of Great Britain and Northern Ireland asked on

Insert from a comma separated list (CSV)


I have a table with 2 columns UserID & BookingID.

I'll know the bookingID and a comma separated list of UserID's.

How would I insert the CSV list with a common BookingID, witout a cursor.

Microsoft SQL Server

Avatar of undefined
Last Comment
Valliappan AN

8/22/2022 - Mon
Vitor Montalvão

With BULK INSERT command. Here's an example:
   FROM Filename -- Provide a string with full path to the filename
         FIELDTERMINATOR =' |',
         ROWTERMINATOR =' |\n'

Open in new window

Andy Green

Sorry my mistake - its not a file its a text string passed into a stored proc.

Vitor Montalvão

Can you give an example of how are those records?
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
Andy Green

BookingID UserID
1                      ab
1                      cd
1                      ef
2                      ab
2                      xy

This is how the table looks the userID are in fact GUIDS

Passed into the proc for the first 3 in the table:

@BookingID as int = 1
@UserID as nvarchar(200) = 'ab,cd,ef'

Vitor Montalvão

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Andy Green

Very cool. Thank you.

Valliappan AN

You can also use XML and Cross apply as follows:

DECLARE @BookingID int = 1
DECLARE @UserID nvarchar(200) = 'ab,cd,ef'

SELECT @BookingID As BookingID,  
     Split.a.value('.', 'VARCHAR(100)') AS UserID
         CAST ('<U>' + REPLACE(@UserID, ',', '</U><U>') + '</U>' AS XML) AS String  
     ) AS A CROSS APPLY String.nodes ('/U') AS Split(a);

Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.