Below function can be used to split comma seperated string, output will be in fom of table.
-- SELECT * FROM dbo.fn_Split ('1,2,3',',')
CREATE FUNCTION [dbo].[fn_Split]
(
@String nvarchar (4000),
@Delimiter nvarchar (10)
)
RETURNS @ValueTable table (ID [int] IDENTITY (1, 1) NOT NULL,[Value] nvarchar(4000))
BEGIN
DECLARE @NextString nvarchar(4000)
DECLARE @Pos int
DECLARE @NextPos int
DECLARE @CommaCheck nvarchar(1)
--Initialize
SET @NextString = ''
SET @CommaCheck = right(@String,1)
--Check for trailing Comma, if not exists, INSERT
--if (@CommaCheck <> @Delimiter )
SET @String = @String + @Delimiter
--Get position of first Comma
SET @Pos = charindex(@Delimiter,@String)
SET @NextPos = 1
--Loop while there is still a comma in the String of levels
WHILE (@pos <> 0)
BEGIN
SET @NextString = substring(@String,1,@Pos - 1)
INSERT INTO @ValueTable ( [Value]) Values (@NextString)
SET @String = substring(@String,@pos +1,len(@String))
SET @NextPos = @Pos
SET @pos = charindex(@Delimiter,@String)
END
RETURN
END
-- SELECT * FROM dbo.fn_Split ('1,2,3',',')
CREATE FUNCTION [dbo].[fn_Split]
(
@String nvarchar (4000),
@Delimiter nvarchar (10)
)
RETURNS @ValueTable table (ID [int] IDENTITY (1, 1) NOT NULL,[Value] nvarchar(4000))
BEGIN
DECLARE @NextString nvarchar(4000)
DECLARE @Pos int
DECLARE @NextPos int
DECLARE @CommaCheck nvarchar(1)
--Initialize
SET @NextString = ''
SET @CommaCheck = right(@String,1)
--Check for trailing Comma, if not exists, INSERT
--if (@CommaCheck <> @Delimiter )
SET @String = @String + @Delimiter
--Get position of first Comma
SET @Pos = charindex(@Delimiter,@String)
SET @NextPos = 1
--Loop while there is still a comma in the String of levels
WHILE (@pos <> 0)
BEGIN
SET @NextString = substring(@String,1,@Pos - 1)
INSERT INTO @ValueTable ( [Value]) Values (@NextString)
SET @String = substring(@String,@pos +1,len(@String))
SET @NextPos = @Pos
SET @pos = charindex(@Delimiter,@String)
END
RETURN
END
No comments:
Post a Comment