section a string

I am creating a function in sql to parse a sting it to a variable number of sections base on a delimiter that is set by a parameter.
Below is the function.

ALTER FUNCTION [dbo].[L_SPLIT]
(
      @P1 varchar(max), -- string to parse
      @P2 int,      -- number of sections
      @P3 varchar(10),-- Delimiter
    @P4 int –- section to return
)
RETURNS varchar(max)
AS
BEGIN
      -- Declare the return variable here
      
Declare @products varchar(Max)
DECLARE  @cleanInput varchar(max)
Declare @TEST VARCHAR(10)
Declare @I int
set @I =1
SET @TEST = '%'+ @P3+'%'
set @products = @P1

--WHILE LEN(@products) > 0

 WHILE  @I <= @P4 and  @I <= @P2

    BEGIN
        SET @cleanInput = SUBSTRING(@products,
                                    0,
                                    PATINDEX(@TEST, @products))

        SET @products = SUBSTRING(@products,
                                  LEN(@cleanInput + @P2) + 1,
                                  LEN(@products))
   set @I = @I + 1
 END
 set @cleanInput = CASE
                WHEN @P4 < @P2 THEN @cleanInput
                Else  @products  
               end
      -- Return the result of the function
      RETURN @cleanInput
END


When I Run
select
          dbo.L_SPLIT('1|20|3|343|44|6|8765',3,'|',1)

it returns  1  which is correct

when I run
        select
          dbo.L_SPLIT('1|20|3|343|44|6|8765',3,'|',2)
it returns  NULL and it should be 20

when I run select
          dbo.L_SPLIT('1|20|3|343|44|6|8765',3,'|',3)
It returns  |3|343|44|6|8765  it should be 3|343|44|6|8765
Stacey FontenotAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

HainKurtSr. System AnalystCommented:
i could not get the logic

select dbo.L_SPLIT('1|20|3|343|44|6|8765',3,'|',1)
it returns  1  which is correct

select dbo.L_SPLIT('1|20|3|343|44|6|8765',3,'|',2)
it returns  NULL and it should be 20 

select dbo.L_SPLIT('1|20|3|343|44|6|8765',3,'|',3)
It returns  |3|343|44|6|8765  it should be 3|343|44|6|8765

Open in new window

0
Stacey FontenotAuthor Commented:
I am trying to break a string into a number of sections base on a delimiter and return the section of my choice
0
HainKurtSr. System AnalystCommented:
ok but the examples you gave does not make sense to me...

for example this
select dbo.L_SPLIT('1|20|3|343|44|6|8765',3,'|',3)
It returns  |3|343|44|6|8765  it should be 3|343|44|6|8765

Open in new window

0
Dustin SaundersDirector of OperationsCommented:
I think I see what you're going for.  Something like:

ALTER FUNCTION [dbo].[L_SPLIT]
(
      @p1 varchar(max), -- string to parse
      @p2 int,      -- number of sections
      @p3 varchar(10),-- Delimiter
	  @p4 int --section to return
)
RETURNS varchar(max)
AS
BEGIN
      -- Declare the return variable here     
	DECLARE @i INT, @result VARCHAR(MAX)
	SET @i = 1

	WHILE @i <= @p2
	BEGIN

		DECLARE @string1 VARCHAR(MAX), @length INT
		IF @i != @p2
		BEGIN
			SET @string1 = (SELECT SUBSTRING(@p1,0,CHARINDEX(@p3,@p1)))
			SET @length = LEN(@string1)
			SET @p1 = (SELECT (SUBSTRING(@p1,@length+2,LEN(@p1))))
		END
		ELSE
		BEGIN
			SET @string1 = @p1
		END

		IF @i = @p4
		BEGIN
			SET @result = @string1
		END

		SET @i = @i + 1

	END

	RETURN @result
END

Open in new window


Returns:

'1', '20', '3|343|44|6|8765'
sqlresults.png
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
SharathData EngineerCommented:
<<
when I run select
          dbo.L_SPLIT('1|20|3|343|44|6|8765',3,'|',3)
It returns  |3|343|44|6|8765  it should be 3|343|44|6|8765 >>
Why it should return 3|343|44|6|8765 and why not just 3?

What is the purpose of 2nd parameter (i.e. sections) in your string?

This function splits the string on the passed delimiter and returns the value at desired location.
CREATE FUNCTION splitString
(@p1 varchar(max),
 @p2 varchar(1),
 @p3 int
)
RETURNS VARCHAR(100) AS 
BEGIN

 DECLARE @string VARCHAR(100)
 
;WITH ToXml AS
    (
        SELECT  CAST(('<td><![CDATA[' + REPLACE(@p1, @p2, ']]></td><td><![CDATA[') + ']]></td>') AS XML) AS XmlData
    ),
   CTE AS (
    SELECT  td.value('.', 'NVARCHAR(255)') AS [value],
            ROW_NUMBER() OVER (ORDER BY (SELECT 1)) rn
    FROM    ToXml
        CROSS APPLY XmlData.nodes('td') A ( td ))
 SELECT @string = value FROM CTE WHERE rn = @p3
 RETURN @string
 END
 GO
 
 SELECT dbo.splitString('1|20|3|343|44|6|8765','|',1); --1
 SELECT dbo.splitString('1|20|3|343|44|6|8765','|',2); --20
 SELECT dbo.splitString('1|20|3|343|44|6|8765','|',3); --3

Open in new window

0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.