Separates a string of characters separated by commas or/or other symbols into a single table data.

Source: Internet
Author: User
Tags rtrim

A very common requirement in our daily development process,

In the front we introduced the [original]sql to convert the comma-separated contents of the field stored in the table into a list form, of course, it is possible to change it in this way, but I have the other way I have been used before, also record it.

In accordance with the Convention, we first look at the effect.

Call: SELECT Id from [fn_stringsplittotable] (' 1,12,36,65,58,56,df ', ', ')

The specific functions are as follows:

-- =============================================
--Call: SELECT Id from [fn_stringsplittotable] (' 1,12,36,65,58,56,df ', ', ')
--Create Date: <create date,,>
--Description: Converts a comma-delimited string into tabular data
-- =============================================
CREATE FUNCTION [dbo]. [Fn_stringsplittotable]
(
@StringX varchar (MAX),
@Split nvarchar (10)
)
RETURNS
@IdsTable TABLE
(
[Id] nvarchar (200)
)
As
BEGIN
DECLARE @Index int
DECLARE @LenIndex int
SET @LenIndex =len (@Split)
SET @Index =charindex (@Split, @StringX, 1)
while (@Index >=1)
BEGIN
IF (Left (@StringX, @Index-1) <> ")
INSERT into @IdsTable SELECT LTRIM (RTRIM (left (@StringX, @Index-1))
SET @StringX =right (@StringX, LEN (@StringX) [email protected] @LenIndex + 1)
SET @Index =charindex (@Split, @StringX, 1)
END
IF (@StringX <> ") INSERT into @IdsTable SELECT LTRIM (RTRIM (@StringX))

RETURN
END

The above calls are separated by commas, and if your string is separated by a/number, modify the calling string directly.

--Call: SELECT Id from [fn_stringsplittotable] (' 1/12/36/65/58/56/df ', '/')

Separates a string of characters separated by commas or/or other symbols into a single table data.

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.