Tuesday, April 27, 2010

Creating a Split() function in Sql Server

There are few functions which we miss as a high level language programmer in databases. One of them is a popular function of dotnet called Split(), which is used to return substrings in a string delimited by a specified character. I used a function to work as Split() in my queries which is shared below:

Alter FUNCTION [dbo].[SplitDelimiter]
(
@String varchar(2000) = null,
@Seperator char(1) = null
)
RETURNS @SeperatedValues Table (
ValueId int identity(1,1),
[Value] varchar(100)
)
AS
BEGIN
While (Charindex(@Seperator,@String)>0)
Begin
Insert Into @SeperatedValues (value)
Select
[Value] = Substring(@String,1,Charindex(@Seperator,@String)-1)
Set @String = Substring(@String,Charindex(@Seperator,@String)+len(@Seperator),len(@String))
End
Insert Into @SeperatedValues (Value)
Select Value = ltrim(rtrim(@String))
Return
END


Using this function
Following query will result in 5 rows containing delimited values in each
[Select ValueId, [Value] from dbo.SplitDelimiter('This: is: a: split: sample', ':')]

ValueId Value
----------- -------------------------------------------
1 This
2 is
3 a
4 split
5 sample

(5 row(s) affected)

No comments:

Post a Comment