SQL Server List Length Function

microsoft, sql server

I know lists aren't good to store in a database, but something came up in which I needed to be able to get the list length of a VARCHAR filed.  Instead of having to loop it each time, I decided to see what kind of functions were already out there.  I found a count string function, but it wasn't exactly what I was looking for, so I took the idea and ran with it.

This function takes a list (VARCHAR) and delimiter (VARCHAR) and returns the number of items in the list.

/*
	UDF_LISTLEN
	==================================================
	Created on 02/19/2008 by Robert Froehling
		- returns the length of a list
		- this was modified from count string function at the link below
		- http://www.sql-server-helper.com/functions/count-string.aspx
*/

CREATE FUNCTION UDF_LISTLEN(
	@list VARCHAR(8000),
	@delim VARCHAR(5))
RETURNS TINYINT
BEGIN
	-- define the vars to use
	DECLARE @modString VARCHAR(8000)
	DECLARE @newString VARCHAR(8000)
	DECLARE @oldStringLen SMALLINT
	DECLARE @modStringLen SMALLINT
	DECLARE @newStringLen SMALLINT
	DECLARE @delimLen TINYINT
	DECLARE @diff TINYINT

	-- set some default vars
	SET @oldStringLen = LEN(@list)
	SET @delimLen = LEN(@delim)
	SET @modString = @list
	SET @modStringLen = LEN(@modString)

	-- if the first part of the string is the delim then remove it
	IF SUBSTRING(@modString, 1, @delimLen) = @delim
	BEGIN
		SET @modString = SUBSTRING(@modString, @delimLen + 1, @oldStringLen - @delimLen)
		SET @modStringLen = LEN(@modString)
	END

	-- if the last part of the string is the delim then remove it
	IF SUBSTRING(@modString, @modStringLen - @delimLen + 1, @delimLen) = @delim
	BEGIN
		SET @modString = SUBSTRING(@modString, 1, @modStringLen - @delimLen)
		SET @modStringLen = LEN(@modString)
	END

	-- count the lengths and setup the diff to return
	SET @newString = REPLACE(@list, @delim, '')
	SET @newStringLen = LEN(@newString)
	SET @diff = @modStringLen - @newStringLen + 1

	RETURN @diff
END

Here is a usage example.

DECLARE @list VARCHAR(500)
DECLARE @delim VARCHAR(1)
SET @list = 'fro,ev,jc,ds'
SET @delim = ','
PRINT master.dbo.udf_listlen(@list, @delim)

Update:  I should point out that I've only tested this on SQL Server 2000.

Benji said:
 
Very smart function
Clean, elegant,fast ...
Good work !
 
posted 57 days ago
Add Comment Reply to: this comment OR this thread
 

Search