January 15, 2010 at 8:42 pm
ALTER FUNCTION [dbo].[SplitCSV](
@csv NVARCHAR(4000),
@delm CHAR(1))
RETURNS @Result TABLE
( Element NVARCHAR(4000))
AS
BEGIN
DECLARE @p INT, @lastP INT, @quit CHAR(1)
SET @p = 1
SET @lastP = 0
SET @quit = 'N'
IF (LEN(@csv) = 0)
BEGIN
SET @quit = 'Y'
END
IF (@csv is null )
BEGIN
SET @quit = 'Y'
END
WHILE @quit = 'N'
BEGIN
SET @p = CHARINDEX(@delm, @csv, @lastP + 1)
IF (@p = 0)
BEGIN
INSERT INTO @Result VALUES (SUBSTRING(@csv, @lastP + 1, LEN(@csv) -
@lastP))
SET @quit = 'Y'
END
ELSE
INSERT INTO @Result VALUES (SUBSTRING(@csv, @lastP + 1, @p - @lastP - 1))
SET @lastP = @p -1
END
RETURN
END
How can I change the above program to dispaly as follow when I type the following select statement
select * from SplitCSV('ab,cd,ef',',')
Result:
ab
ab,cd
ab,cd,ef
January 15, 2010 at 8:46 pm
Would you share with us why you want to do this unusual thing first?
--Jeff Moden
Change is inevitable... Change for the better is not.
January 15, 2010 at 9:44 pm
Jeff Moden (1/15/2010)
Would you share with us why you want to do this unusual thing first?
Hi Jeff,
The OP needs to set the posted function (may created for another reason) to their requirement.
Plain solution with tally table (article)
Declare @Parameter varchar(max),
@delm char(1)
set @Parameter = 'ab,bc,cd'
set @delm = ','
set @Parameter = @delm+@Parameter+@delm
SELECT SUBSTRING(@Parameter,N+1,CHARINDEX(',',@Parameter,N+1)-N-1)
FROM dbo.Tally /*Refer Jeff article to create this number table*/
WHERE N < LEN(@Parameter)
AND SUBSTRING(@Parameter,N,1) = @delm
January 16, 2010 at 8:05 am
arun.sas (1/15/2010)
Jeff Moden (1/15/2010)
Would you share with us why you want to do this unusual thing first?Hi Jeff,
The OP needs to set the posted function (may created for another reason) to their requirement.
Plain solution with tally table (article)
Declare @Parameter varchar(max),
@delm char(1)
set @Parameter = 'ab,bc,cd'
set @delm = ','
set @Parameter = @delm+@Parameter+@delm
SELECT SUBSTRING(@Parameter,N+1,CHARINDEX(',',@Parameter,N+1)-N-1)
FROM dbo.Tally /*Refer Jeff article to create this number table*/
WHERE N < LEN(@Parameter)
AND SUBSTRING(@Parameter,N,1) = @delm
Heh... thanks Arun and, yeah, I know how to do it with a Tally table 😛 but I really wanted to know why the OP wanted to do this. Once most OPs have their answer, they never come back to share the real reason. Knowing the real reason for such a requirement is as important to me as the correct answer is to the OP. Be patient, my friend. 😉
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply