SQL Function For Spliting a String in SQL SERVER
In SQL Server we do not have a built in function for splitting a string with any character. So we need to write the query for splitting a string in SQL. Here I am creating a function for splitting a string and getting the output data in a table.
CREATE FUNCTION [dbo].[fnSplitString] ( @MyArray VARCHAR(8000), @separator CHAR(1) )
RETURNS @RetTable TABLE
(StrValue VARCHAR(256))
AS
BEGIN
DECLARE @SeperatorString
VARCHAR(10);
SET @SeperatorString = '%' + @separator + '%'
DECLARE @separator_position
INT
DECLARE @array_value VARCHAR(1000)
SET @MyArray = @MyArray + @separator
WHILE PATINDEX( @SeperatorString , @MyArray) <> 0
BEGIN
SELECT @separator_position
= PATINDEX(@SeperatorString , @MyArray)
SELECT @array_value = LEFT(@MyArray, @separator_position -
1)
INSERT @RetTable VALUES ( CAST(@array_value AS VARCHAR(256)) )
SELECT @MyArray = STUFF(@MyArray, 1, @separator_position, '')
END
RETURN
END
Example 1 :
SELECT StrValue FROM dbo.[fnSplitString]('data1,data2,data3,data4',',')
The result will be
DECLARE @MyString VARCHAR(1000);
SET @MyString = 'data1;data2;data3;data4;1;2;3'
SELECT StrValue FROM dbo.[fnSplitString](@MyString,';')
No comments:
Post a Comment