Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL split string based on delimiter

I have some data that I would like to split based on a delimiter that may or may not exist.

Example data:

John/Smith Jane/Doe Steve Bob/Johnson 

I am using the following code to split this data into First and Last names:

SELECT SUBSTRING(myColumn, 1, CHARINDEX('/', myColumn)-1) AS FirstName,        SUBSTRING(myColumn, CHARINDEX('/', myColumn) + 1, 1000) AS LastName FROM   MyTable 

The results I would like:

FirstName---LastName John--------Smith Jane--------Doe Steve-------NULL Bob---------Johnson 

This code works just fine as long as all the rows have the anticipated delimiter, but errors out when a row does not:

"Invalid length parameter passed to the LEFT or SUBSTRING function." 

How can I re-write this to work properly?

like image 215
Sesame Avatar asked Feb 14 '14 00:02

Sesame


People also ask

How split a string in SQL query?

The STRING_SPLIT(string, separator) function in SQL Server splits the string in the first argument by the separator in the second argument. To split a sentence into words, specify the sentence as the first argument of the STRING_SPLIT() function and ' ' as the second argument. FROM STRING_SPLIT( 'An example sentence.


2 Answers

May be this will help you.

SELECT SUBSTRING(myColumn, 1, CASE CHARINDEX('/', myColumn)             WHEN 0                 THEN LEN(myColumn)             ELSE CHARINDEX('/', myColumn) - 1             END) AS FirstName     ,SUBSTRING(myColumn, CASE CHARINDEX('/', myColumn)             WHEN 0                 THEN LEN(myColumn) + 1             ELSE CHARINDEX('/', myColumn) + 1             END, 1000) AS LastName FROM MyTable 
like image 131
sureshhh Avatar answered Sep 21 '22 20:09

sureshhh


For those looking for answers for SQL Server 2016+. Use the built-in STRING_SPLIT function

Eg:

DECLARE @tags NVARCHAR(400) = 'clothing,road,,touring,bike'    SELECT value   FROM STRING_SPLIT(@tags, ',')   WHERE RTRIM(value) <> '';   

Reference: https://msdn.microsoft.com/en-nz/library/mt684588.aspx

like image 26
raga Avatar answered Sep 19 '22 20:09

raga