Splitting a string into a split character in SQL

Source: Internet
Author: User

Create a function
1 SETAnsi_nulls on2 GO3 4 SETQuoted_identifier on5 GO6 7 Create FUNCTION [dbo].[F_split]8  (9      @SplitString nvarchar(Max),--Source StringTen      @Separator nvarchar(Ten)=' '  --delimited symbols, default to spaces One  ) A  RETURNS @SplitStringsTable TABLE  --data table for output -  ( -      [ID] int Identity(1,1), the      [value] nvarchar(Max) -  ) -   as -  BEGIN +      DECLARE @CurrentIndex int; -      DECLARE @NextIndex int; +      DECLARE @ReturnText nvarchar(Max); A  at      SELECT @CurrentIndex=1; -       while(@CurrentIndex<=Len(@SplitString)) -          BEGIN -              SELECT @NextIndex=charindex(@Separator,@SplitString,@CurrentIndex); -              IF(@NextIndex=0 OR @NextIndex  is NULL) -                  SELECT @NextIndex=Len(@SplitString)+1; in                  SELECT @ReturnText=substring(@SplitString,@CurrentIndex,@NextIndex-@CurrentIndex); -                  INSERT  into @SplitStringsTable([value])VALUES(@ReturnText); to                  SELECT @CurrentIndex=@NextIndex+1; +              END -      RETURN; the  END * GO

Use:

SELECT * from F_split (' 1,2,3,4,5 ', ', ')

  

SELECT * from Tb_sysuser u where u.id in (select value from dbo. F_split (' 1,2,3,4 ', ', '))

  

Splitting a string into a split character in SQL

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.