Showing posts with label How to split comma delimited string in SQL Server?. Show all posts
Showing posts with label How to split comma delimited string in SQL Server?. Show all posts

How to split comma delimited string in SQL Server 2008?

Step 1: 

Create a function that will accept the "text string" and "character" where we want to split the string:

ALTER FUNCTION [dbo].[funSplit]
(
@Texto varchar(max),
@Splitter varchar(3)
)
RETURNS
@Lista TABLE
(
rowData varchar(8000)
)
AS
BEGIN
DECLARE @Pos Smallint
While len(@Texto)>0 BEGIN
  SET @Pos = Patindex('%'+@Splitter+'%',@Texto)
  
  IF @Pos > 0 BEGIN
   INSERT INTO @Lista
   SELECT left(@Texto, @Pos-1)
  
   SET @Texto = right(@Texto, len(@Texto)-@Pos)
  END
  ELSE BEGIN
   INSERT INTO @Lista
   SELECT @Texto
  
   SET @Texto = ''
  END
End
RETURN
END GO


Step 2: 

Now call the function pass the "sample string" & "character" to split as shown below:

select * from dbo.funSplit('sql-server-query-world','-')


The output of the query would look like below, that is our desired output:

How to split comma delimited string in SQL Server 2008?