To split a string function in a SQL Server database

Source: Internet
Author: User
Tags split strlen

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.