Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 

SQL Function to Split Comma Separated Values and Insert into Table

By Lokeshkumar, 2010/11/30

The Below SQL Function can be used to Insert comma Separated values into Table

/****** Object: UserDefinedFunction [dbo].[CommaSplit] Script Date: 11/07/2010 15:14:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Lokeshkumar
-- Create date: 11/07/2010
-- Description: Return Comma Separated Strings as DataTable
-- =============================================
ALTER FUNCTION [dbo].[CommaSplit]
(
@InputString VARCHAR(MAX)
)
RETURNS
@OutputTable TABLE
(
-- Add the column definitions for the TABLE variable here
Val VARCHAR(MAX)
)
AS
BEGIN
-- Fill the table variable with the rows for your result set
DECLARE @Val VARCHAR(MAX),@Pos INT,@Len INT
SET @Len = LEN(@InputString)

SET @Pos=0
WHILE (CHARINDEX(',',@InputString,@Pos)-@Pos) > 0
BEGIN

SET @Val = SUBSTRING(@InputString,@Pos,(CHARINDEX(',',@InputString,@Pos)-@Pos))

INSERT INTO @OutputTable(Val)
SELECT @Val
SET @Pos = CHARINDEX(',',@InputString,@Pos)+1

END
IF @Pos <= @Len
BEGIN

SET @Val = SUBSTRING(@InputString,@Pos,(@Len+1)-@Pos)

INSERT INTO @OutputTable(Val)
SELECT @Val

END

RETURN
END

Total article views: 3775 | Views in the last 30 days: 30
 
Related Articles
FORUM

Searching for URL contents using CHARINDEX

Providing CHARINDEX parameter from table

BLOG

String Manipulation - CHARINDEX()

I see charindex used quite commonly in string manipulation.  What I rarely see used is the optional ...

FORUM

charindex or like condition

Hi iam executing the below query which is not executing even for hours also if i replcae like instea...

FORUM

Begin Tran...Commit Tran with Exec SQL Insert Cmd

BEGIN TRAN, COMMIT TRAN, ROLLBACK

FORUM

problems using charindex function

charindex does not work they way i think it should work :)

Tags
 
Contribute

Join the most active online SQL Server Community

SQL knowledge, delivered daily, free:

Email address:  

You make SSC a better place

As a member of SQLServerCentral, you get free access to loads of fresh content: thousands of articles and SQL scripts, a library of free eBooks, a weekly database news roundup, a great Q & A platform… And it’s our huge, buzzing community of SQL Server Professionals that makes it such a success.

Join us!

Steve Jones
Editor, SQLServerCentral.com

Already a member? Jump in:

Email address:   Password:   Remember me: Forgotten your password?
Steve Jones