Solved

SQL server splitting a comma separated value

Posted on 2016-09-03
3
22 Views
Last Modified: 2016-10-22
i want code for splitting a commaseparated list int a temporary table in sql server. can you help me
0
Comment
Question by:Gopakumar Pandarikkal
3 Comments
 
LVL 33

Accepted Solution

by:
ste5an earned 250 total points
ID: 41782808
There are two built-in ways:

DECLARE @Text NVARCHAR(255) = N'1,2,<td>test</td>,4';

-- SQL Server 2016
SELECT	SS.*
FROM	STRING_SPLIT(@Text, ',') SS;

-- Before
WITH ToXml AS
	(
		SELECT	CAST(('<td><![CDATA[' + REPLACE(@Text, ',', ']]></td><td><![CDATA[') + ']]></td>') AS XML) AS XmlData
	)
	SELECT	td.value('.', 'NVARCHAR(255)') AS [value]
	FROM	ToXml
		CROSS APPLY	XmlData.nodes('td') A ( td );

Open in new window


The XML method is not optimal, but for normal purposes fast enough.
2
 
LVL 40

Assisted Solution

by:Sharath
Sharath earned 250 total points
ID: 41787495
try this.
DECLARE  @s VARCHAR(100)

SELECT @s = 'Apples,Oranges,Mangoes,Grapes';

WITH cte
     AS (SELECT ROW_NUMBER()
                  OVER(ORDER BY p1.NUMBER) AS sr,
                NUMBER
         FROM   MASTER..spt_values p1
         WHERE  p1.TYPE = 'p'
                AND p1.NUMBER BETWEEN 1 AND LEN(@s) + 2
                AND SUBSTRING(',' + @s + ',',p1.NUMBER,1) = ',')
SELECT SUBSTRING(' ' + @s,a.NUMBER + 1,b.NUMBER - a.NUMBER - 1) AS Fruit
FROM   cte a
       INNER JOIN cte b
         ON b.sr = a.sr + 1

/*
Fruit
Apples
Oranges
Mangoes
Grapes
*/

Open in new window

0

Featured Post

U.S. Department of Agriculture and Acronis Access

With the new era of mobile computing, smartphones and tablets, wireless communications and cloud services, the USDA sought to take advantage of a mobilized workforce and the blurring lines between personal and corporate computing resources.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
SQL profiler equivalent in MS-Access 3 43
Help with SQL Server Stoplist 2 18
MSSQL: Replace text (typo) 7 33
TSQL - IF ELSE? 3 29
For both online and offline retail, the cross-channel business is the most recent pattern in the B2C trade space.
I have a large data set and a SSIS package. How can I load this file in multi threading?
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Via a live example, show how to shrink a transaction log file down to a reasonable size.

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now