USE [Test] GO /****** Object: UserDefinedFunction [dbo].[GetDistinct] Script Date: 12/09/2015 17:09:29 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER function [dbo].[GetDistinct](@str varchar(max)) returns varchar(max) as begin declare @ret varchar(max) declare @temp varchar(max) set @str=@str+';' while(charindex(';;',@str)>0) begin set @str= replace(@str,';;',';') end set @temp= left(@str,charindex(';',@str)) while(charindex(';'+@temp,';'+isnull(@ret,''))=0 and len(@str)>0) begin set @ret=isnull(@ret,'')+@temp set @str=substring(@str,charindex(';',@str)+1,len(@str)) if (len(@str)>0) begin set @temp= left(@str,charindex(';',@str)) end end set @ret=left(@ret,len(@ret)-1) return @ret end