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')

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