A 'Handy Code' for all - Function that splits string
Database developers often need to split a string. When we need to do so we keep on searching online for the solution as we always look for a quick fix. This code snippet has the function that splits a string and returns the plain text. Also the snippet has the code block where we can format the string. Hope this code will be a very quick reference.
Developers often splits the value of a column at front end side but in some cases we need to do it on database. In this code snippet I have written a function that simply splits a string and returns the plain text.
Also the snippet has the block where developers can write their own code to format the string.
So lets start with the code. The function is written bellow and I hope its very much self explanatory and can be used as a quick reference. Just copy and paste the code on your database server and execute it.
CREATE FUNCTION [dbo].[GET_SPLITTED_STRING]
(
@input VARCHAR(1000),
@delimiter VARCHAR(10)
)
RETURNS VARCHAR(1000)
AS
BEGIN
DECLARE @mainString VARCHAR(1000) = null;
DECLARE @output VARCHAR(1000) = '';
WHILE LEN(@input) > 0
BEGIN
IF PATINDEX('%'+ @delimiter +'%',@input) > 0
BEGIN
SET @mainString = SUBSTRING(@input, 0, PATINDEX('%'+ @delimiter +'%',@input))
SET @input = SUBSTRING(@input, LEN(@mainString + @delimiter) + 1, LEN(@input))
--Devs can do the formatting part here.
SET @output = @output + CHAR(13)+ @mainString -- CHAR(13) To Create New Line
END
ELSE
BEGIN
SET @mainString = @input
SET @input = NULL
--Devs can do the formatting part here.
SET @output = @output + CHAR(13)+ @mainString -- CHAR(13) To Create New Line
END
END
RETURN @output
END
Now to execute the function use the following code.
DECLARE @result VARCHAR(1000);
EXEC @result = [dbo].[GET_SPLITTED_STRING] @input = 'String 1||String 2||String 3', @delimiter = '||';
--Returns the result in the message tab.
PRINT @result;
That is all about it. Hope it will be useful.