Specific ways to split string functions in a SQL Server database:
CREATE FUNCTION uf_strsplit ' 1.1.2.50 ', '. '
(@origStr varchar (7000),--the string to be split
@markStr varchar (100))--split mark, such as ', '
RETURNS @splittable Table
(
STR_ID varchar (4000) not NULL,--numbered ID
String varchar not NULL--split strings
)
As
BEGIN
declare @strlen int, @postion int, @start int, @sublen int,
@TEMPstr varchar, @TEMPid int
SELECT @strlen =len (@origStr), @start =1, @sublen =0, @postion = 1,
@TEMPstr = ', @TEMPid =0
if (Right (@origStr, 1) <> @markStr)
Begin
Set @origStr = @origStr + @markStr
End
while ((@postion <= @strlen) and (@postion!=0))
BEGIN
IF (CHARINDEX (@markStr, @origStr, @postion)!=0)
BEGIN
SET @sublen =charindex (@markStr, @origStr, @postion)-@postion;
End
ELSE
BEGIN
SET @sublen = @strlen-@postion +1;
End
IF (@postion <= @strlen)
BEGIN
SET @TEMPid = @TEMPid +1;
SET @TEMPstr =substring (@origStr, @postion, @sublen);
INSERT into @splittable (str_id,string)
VALUES (@TEMPid, @TEMPstr)
IF (CHARINDEX (@markStr, @origStr, @postion)!=0)
BEGIN
SET @postion =charindex (@markStr, @origStr, @postion) +1
End
ELSE
BEGIN
SET @postion = @postion +1
End
End
End
Return
End
For example: SELECT * from Uf_strsplit (' 1,1,2,50 ', ', ')
Output results:
str_id string
1 1
2 1
3 2
4 50