set ANSI_NULLS ON set QUOTED_IDENTIFIER ON go CREATE FUNCTION [dbo].[fn_ParseCommaDelimitedList] ( @CommaDelimitedList varchar(4000) ) RETURNS @TableVar TABLE (ItemID int NOT NULL ) AS BEGIN DECLARE @IDListPosition int DECLARE @IDList varchar(4000) DECLARE @ArrValue varchar(4000) SET @IDList = COALESCE(@CommaDelimitedList, '') IF @IDList <> '' BEGIN -- Add comma to end of list so user doesn't have to SET @IDList = @IDList + ',' -- Loop through the comma demlimted string list WHILE PATINDEX('%,%' , @IDList ) <> 0 BEGIN SELECT @IDListPosition = PATINDEX('%,%' , @IDList) SELECT @ArrValue = LEFT(@IDList, @IDListPosition - 1) -- Insert parsed ID into TableVar for "where in select" INSERT INTO @TableVar (ItemID) VALUES (CONVERT(int, @ArrValue)) -- Remove processed string SELECT @IDList = STUFF(@IDList, 1, @IDListPosition, '') END END RETURN END