I\'m working with a SQL Server database. I have a column which contains a delimited list, and I need to write a query which splits the values of the list into rows. From bro
I would just take one of the many functions that creates a table and instead of having it return the value put it in a table variable. Then use the table variable. Here is one example that returns a table.
http://www.codeproject.com/KB/database/SQL_UDF_to_Parse_a_String.aspx
example using the built in master..spt_values table
DECLARE @String VARCHAR(1000)
SELECT @String ='1,4,77,88,4546,234,2,3,54,87,9,6,4,36,6,9,9,6,4,4,68,9,0,5'
SELECT SUBSTRING(',' + @String + ',', Number + 1,
CHARINDEX(',', ',' + @String + ',', Number + 1) - Number -1)AS VALUE
FROM master..spt_values
WHERE Type = 'P'
AND Number <= LEN(',' + @String + ',') - 1
AND SUBSTRING(',' + @String + ',', Number, 1) = ','
GO
See here for more: Split A String By Using A Number Table
You can use recursive CTE to progressively extract one item
Sample table
create table aTable(a int identity primary key, b int, c varchar(100))
insert aTable values (1, 'this is a test string')
insert aTable values (1, 'this is another test string')
insert aTable values (2, 'here is a test string to put the others to shame')
insert aTable values (4, '')
insert aTable values (5, null)
insert aTable values (5, '-the end- ')
The query
;with tmp(a, b, c, position, single) as (
select a, b,
STUFF(c, 1, CHARINDEX(' ', c + ' .'), ''),
1,
convert(nvarchar(max),left(c, CHARINDEX(' ', c + ' .') -1))
from aTable
union all
select a, b,
STUFF(c, 1, CHARINDEX(' ', c + ' .'), ''),
position+1,
convert(nvarchar(max),left(c, CHARINDEX(' ', c + ' .') -1))
from tmp
where c > '')
select a, b, single, position
from tmp
order by a, position
Notes:
' .'
is required because SQL Server normally does not see trailing spaces as significant.a
and b
preserved in the output, with the column c
being split into single
and an extra column to indicate the position.For sql Server >= 2016 you can use string_split as below:
SELECT * FROM string_split('Hello John Smith', ' ')
Output
+-------+
| value |
+-------+
| Hello |
| John |
| Smith |
+-------+
Here's a user-defined parsing function that enables SQL Server that also performs similarly to the VB "Split" function. Designed for interactive leveraging; for example, to parse data within a Stored Procedure called from an external API.
https://gallery.technet.microsoft.com/scriptcenter/User-def-function-enabling-98561cce