Alines UDF - String Split

topic: 

The ufn_Alines() UDF for SQL Server is similar to the VFP Alines() function but w/o additional parameters.

$SAMPLECODE$

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

-- ufn_Alines ---
IF EXISTS (SELECT * FROM   sysobjects WHERE  name = N'ufn_Alines')
	DROP FUNCTION ufn_Alines
GO
CREATE FUNCTION ufn_Alines 
	(@Str varchar(8000),
	 @separator varchar(16)=',') 
RETURNS @TableArray TABLE 
	(ik int Identity, 
	 Item varchar(128))
AS
/* Splits passed string into items based on the specified separator string
 Parameters:
	@str  - The string to split
	@separator - The separator string ( comma is default)
 Returns table variable with two columns:
   ik int - Item number 	
   Item varchar(128) - Item itself
*/

BEGIN
	DECLARE @Item varchar(128), @pos int
	WHILE DATALENGTH(@str) > 0
	BEGIN
		SET @pos = CHARINDEX(@separator, @str)
		IF @pos = 0 
			SET @pos = DATALENGTH(@str)+1
			
		SET @Item = LEFT(@str, @pos -1 )
		SET @str = SUBSTRING(@str, @pos + DATALENGTH(@separator), 8000)
		INSERT INTO @TableArray (Item) VALUES(@Item)
	END
	
	RETURN

END

GO

-- Sample of using ufn_Alines UDF
SELECT * FROM dbo.ufn_Alines('The quick brown fox jumps over the lazy dog', SPACE(1))

Comments

Alternative ways to split a string suggested by readers:

By George - Posted on April 23rd, 2009

There is a better/faster way to split strings in T-SQL (if you have a numbers table in your database)

http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/the-ten-most-asked-sql-server-questions--1

<br>

By Niikola - Posted on September 2nd, 2009

See at http://forum.lessthandot.com/viewtopic.php?f=17&t=7566

Hello Sergey,
This topic is very popular among sql programmers since all we meet such cases occasionally.
Addition to your user function, I want to share alternative methods like <a href="http://www.kodyaz.com/articles/t-sql-convert-split-delimeted-string-as-rows-using-xml.aspx" target="_blank">SQL Split String Function using XML</a> or <a href="http://www.kodyaz.com/articles/sql-server-t-sql-split-function.aspx" target="_blank">Recursive T-SQL Split Function</a>.

Altought there might be performance considerations with these udf's, I believe those scripts might help at least t-sql approach of a developer.

<a href="http://sqlblog.com/blogs/aaron_bertrand/default.aspx">Aaron Bertrand</a> posted interesting comparison of diiffrent methods of <a href="http://sqlblog.com/blogs/aaron_bertrand/archive/2010/07/07/splitting-a-list-of-integers-another-roundup.aspx">Splitting a list of integers : another roundup </a>