#TempTable from comma separated textdata

Berhan Karagoez
Berhan Karagoez used Ask the Experts™
on
I want to declare a list:

DECLARE @myList     nvarchar(max)  = '1,2,3~4,5,6';


Do cross appply (or similar) to get:

col 1, col 2, col 3
1         2        3
4         5        6

How would you do that?

/BK
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
lcohanDatabase Analyst

Commented:
Below is an example similar to your request but from a csv file which is essentially close to what you need:

--create a table to host imported data
CREATE TABLE #SampleOutput
(
[CreatedDate] varchar(50) null,
[FailureReason] varchar(255) null,
[FromUser] varchar(50) null,
[QSource] varchar(255) null
)
GO


--Now run following script to load all the data from CSV to database table. If there is any error in any row it will be not inserted but other rows will be inserted.
BULK
INSERT #SampleOutput
FROM 'c:\SampleOutput.csv'
WITH
(
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
GO

--Check the content of the table.
SELECT * FROM #SampleOutput;

DROP TABLE #SampleOutput;

Open in new window

Author

Commented:
No, I do not want to use BULK insert of any kind, sorry I forgot to mention this.
Software Team Lead
Commented:
try this:

DECLARE @myList nvarchar(max)  = '1,2,3~4,5,6~7,8,9~10,11,12';

declare @xml xml = cast(concat('<root><row>', replace(@myList,'~','</row><row>'), '</row></root>') as xml)

;with cte as
(
	Select f.value('text()[1]','NVARCHAR(MAX)') v from @xml.nodes('//row') t(f)
)
Select
parsename(replace(v,',','.'),3) col1,
parsename(replace(v,',','.'),2) col2,
parsename(replace(v,',','.'),1) col3
from cte

Open in new window

Author

Commented:
Yes Ryan - that is the solution.

I've also used xml to solve this but your solution was better and shorter code as well, plus it did exactly what I wanted!


Thank you.
Ryan ChongSoftware Team Lead

Commented:
Coool great

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial