Click here to Skip to main content
12,946,304 members (51,474 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

4.5K views
2 bookmarked
Posted 18 Jun 2014

Split a String with Specific Separator Character

, 18 Jun 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
T-SQL scripts: Write a table function to split a string with specific separator character

Introduction

Write a table function to split a string with specific separator character.

Example:

SELECT * FROM dbo.Split('john, peter, mary', ',')

And result:

  • john
  • peter
  • mary
CREATE FUNCTION [dbo].[Split](@array NVARCHAR(MAX),@separator char(1))
RETURNS @tbl TABLE (string nvarchar(128) NOT NULL) AS
BEGIN
      DECLARE @pos      int,
              @textpos  int,
              @chunklen smallint,
              @str      nvarchar(MAX),
              @tmpstr   nvarchar(MAX),
              @leftover nvarchar(MAX)

      SET @textpos = 1
      SET @leftover = ''
      WHILE @textpos <= datalength(@array) / 2
      BEGIN
         SET @chunklen = 4000 - datalength(@leftover) / 2
         SET @tmpstr = ltrim(@leftover + substring(@array, @textpos, @chunklen))
         SET @textpos = @textpos + @chunklen

         SET @pos = charindex(@separator, @tmpstr)
         WHILE @pos > 0
         BEGIN
            SET @str = substring(@tmpstr, 1, @pos - 1)
            INSERT @tbl (string) VALUES(convert(nvarchar(20), @str))
            SET @tmpstr = ltrim(substring(@tmpstr, @pos + 1, len(@tmpstr)))
            SET @pos = charindex(@separator, @tmpstr)
         END

         SET @leftover = @tmpstr
      END

      IF ltrim(rtrim(@leftover)) <> ''
         INSERT @tbl (string) VALUES(convert(nvarchar(Max), @leftover))

      RETURN
   END
GO

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Ngo Thanh Tung - Softech
Technical Writer Softech
Vietnam Vietnam
/* Life runs on code */

You may also be interested in...

Comments and Discussions

 
SuggestionEasy way to split string Pin
Member 107271924-Jul-14 0:15
memberMember 107271924-Jul-14 0:15 
SuggestionI have something similar . Check if the below code is works for you. Pin
Raju_B19-Jun-14 4:16
memberRaju_B19-Jun-14 4:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170518.1 | Last Updated 18 Jun 2014
Article Copyright 2014 by Ngo Thanh Tung - Softech
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid