SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO /* By kudychen 2011-9-28 */ CREATE function [dbo]. [SplitString] ( @ Input nvarchar (max), -- input string to be separated @ Separator nvarchar (max) = ',', -- a string that delimit the substrings in the input string @ RemoveEmptyEntries bit = 1 -- the return value does not include array elements that contain an empty string ) Returns @ TABLE table ( [Id] int identity (1, 1 ), [Value] nvarchar (max )) As Begin Declare @ Index int, @ Entry nvarchar (max) Set @ Index = charindex (@ Separator, @ Input) While (@ Index> 0) Begin Set @ Entry = ltrim (rtrim (substring (@ Input, 1, @ Index-1 ))) If (@ RemoveEmptyEntries = 0) or (@ RemoveEmptyEntries = 1 and @ Entry <> '') Begin Insert into @ TABLE ([Value]) Values (@ Entry) End Set @ Input = substring (@ Input, @ Index + datalength (@ Separator)/2, len (@ Input )) Set @ Index = charindex (@ Separator, @ Input) End Set @ Entry = ltrim (rtrim (@ Input )) If (@ RemoveEmptyEntries = 0) or (@ RemoveEmptyEntries = 1 and @ Entry <> '') Begin Insert into @ TABLE ([Value]) Values (@ Entry) End Return End |