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?
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With