Click here to monitor SSC
SQLServerCentral is supported by Redgate
 
Log in  ::  Register  ::  Not logged in
 
 
 

Get your favorite SSC scripts directly in SSMS with the free SQL Scripts addin. Search for scripts directly from SSMS, and instantly access any saved scripts in your SSC briefcase from the favorites tab.
Download now (direct download link)

SQL Function to Split Comma Separated Values and Insert into Table

By Lokeshkumar,

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: 4139 | Views in the last 30 days: 2
 
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

Problem segregating third occurence from a column

Charindex ,substring

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

Tags
 
Contribute