0

This is my code for function:

CREATE FUNCTION [dbo].[fSubString](@pStudentID VARCHAR(1000))
RETURNS @vStringTable TABLE( StudentNo int)
AS
BEGIN
   DECLARE @pStart INT, -- for substring , start
           @pLength INT; -- Length for @pStudent

   SET @pStart = 1;
   SET @pLength = DATALENGTH(@pStudentID);

   WHILE(@pStart <= @pLength)
   BEGIN
       INSERT INTO @vStringtable    
       VALUES(SUBSTRING(@pStudentID, @pStart, CHARINDEX(',', @pStudentID, 1) - 1))

       SET @pStart = CHARINDEX(',', @pStudentID, 1) + @pStart;
   END

   RETURN
END

Execute this function

Select * from dbo.fSubString('1,4,2,3,6,5,4,3')

Works fine.

But this execution of that function causes problems:

 Select * from dbo.fSubString('33,4,44,3,6,5,74,3')
3
  • Substring Select * from dbo.fSubString('1,4,2,3,6,5,4,3') its work but Select * from dbo.fSubString('3344,4444,44,3,6,5,74,3') not substring why Commented May 13, 2014 at 17:20
  • 3
    this part of your function: CHARINDEX(',', @pStudentID, 1) is fixed. So the length of your substring isn't taking into account the actual length between commas. It works in your first example because every element is a one char length unlike your second example Commented May 13, 2014 at 17:30
  • ok ,how fixed this problem Commented May 13, 2014 at 17:37

1 Answer 1

2

There are a ton of better ways to split strings. Do not re-invent the wheel.

See this article from Aaron Bertrand for a list of know ways.

http://sqlperformance.com/2012/07/t-sql-queries/split-strings

For instance, if your data is XML safe, use this function. Great for small data sets. See performance metrics at end of article.

CREATE FUNCTION dbo.SplitStrings_XML
(
   @List       NVARCHAR(MAX),
   @Delimiter  NVARCHAR(255)
)
RETURNS TABLE
WITH SCHEMABINDING
AS
   RETURN 
   (  
      SELECT Item = y.i.value('(./text())[1]', 'nvarchar(4000)')
      FROM 
      ( 
        SELECT x = CONVERT(XML, '<i>' 
          + REPLACE(@List, @Delimiter, '</i><i>') 
          + '</i>').query('.')
      ) AS a CROSS APPLY x.nodes('i') AS y(i)
   );
GO

Here are the results of a sample call. The function was stored in msdb.

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Good answer. Here is a sqlfiddle for your function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.