if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[udf_ListToTable]') and xtype in (N'FN', N'IF', N'TF')) drop function [dbo].[udf_ListToTable] GO CREATE FUNCTION [dbo].[udf_ListToTable] ( @LIST VARCHAR(4000), @DELIMITER VARCHAR(10) = ',' ) RETURNS @ListTable TABLE ( Item VARCHAR(200) ) AS BEGIN DECLARE @LenDel INT DECLARE @Pos INT DECLARE @Item VARCHAR(200) --Get the length of the delimiter, use hack to get around LEN(' ') = 0 issue SET @LenDel = LEN(@DELIMITER + '|') - 1 SET @Pos = CHARINDEX(@DELIMITER, @LIST) WHILE @Pos > 0 BEGIN --Get the item SET @Item = SUBSTRING(@LIST, 1, @Pos-1) --Add it to the table (if not empty string) IF LEN(LTRIM(@Item)) > 0 INSERT @ListTable (Item) VALUES (LTRIM(@Item)) --Remove the item from the list SET @LIST = STUFF(@LIST, 1, @Pos+@LenDel-1, '') --Get the position of the next delimiter SET @Pos = CHARINDEX(@DELIMITER, @LIST) END --Add the last item to the table (if not empty string) IF LEN(LTRIM(@LIST)) > 0 BEGIN INSERT @ListTable (Item) VALUES (LTRIM(@LIST)) END RETURN END GO