#TempTable from comma separated textdata

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
Berhan KaragoezCreatorAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

lcohanDatabase AnalystCommented:
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

Berhan KaragoezCreatorAuthor Commented:
No, I do not want to use BULK insert of any kind, sorry I forgot to mention this.
Ryan ChongSoftware Team LeadCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Berhan KaragoezCreatorAuthor 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 LeadCommented:
Coool great
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
SQL

From novice to tech pro — start learning today.