Reputation: 11
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')
Upvotes: 0
Views: 74
Reputation: 14925
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.
Upvotes: 2