Alines UDF - String Split
The ufn_Alines() UDF for SQL Server is similar to the VFP Alines() function but w/o additional parameters.
| This is sample code. Add error handling and adjust to your requirements as necessary. |
-- 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))
Re: Alines UDF - String Split
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-...
By Niikola - Posted on September 2nd, 2009
See at http://forum.lessthandot.com/viewtopic.php?f=17&t=7566
Alternative functions and scripts
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 SQL Split String Function using XML or Recursive T-SQL Split Function.
Altought there might be performance considerations with these udf's, I believe those scripts might help at least t-sql approach of a developer.
Aaron Bertrand post about splitting a list of integers
Aaron Bertrand posted interesting comparison of diiffrent methods of Splitting a list of integers : another roundup